0

I have a linq query.

var query = (from s in dc.ClassInfos
                 where s.ClassName == tbSubject.Text
                 select new{
                  location = s.ClassLocation,
                  Date = s.ClassDate
                 });

Now I like to assign the location value to a local variable. Can you help me how to do this?

1
  • Which location? You could have multiple results. Commented Sep 7, 2011 at 20:15

3 Answers 3

2

you query returns an IEnumerable of an anonymous class - not just a single value. If you wanted to assign the first location value (provided there is one) you could do:

var location =  query.First().location;

If you want all locations in a list on the other hand this should work:

var locations =  query.Select( x=> x.location).ToList();
Sign up to request clarification or add additional context in comments.

Comments

2
var location = query.First().location;

But I would write

var location = (from s in dc.ClassInfos
                where s.ClassName == tbSubject.Text
                select s.ClassLocation).FirstOrDefault();

because you don't need to select Date if you only use location.

Comments

0
var localVar = new List<string>();  

foreach (var item in query)
{
  localvars.add(item.location);
}

1 Comment

There are much more elegant ways of doing this. Also, I don't think this answers OPs question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.