views:

67

answers:

4

I am trying the to query my Status Update repository using the following

    var result = (from s in _dataContext.StatusUpdates
                  where s.Username == "friend1" && s.Username == "friend2" etc...
                  select s).ToList();

Insead of using s.Username == "friendN" continously is there anyway I can pass a list or array or something like that rather that specifying each one, or can i use a foreach loop in the middle of the query.

Thanks

+1  A: 

Sorry guys, obviously didnt search well enough before i posted.

Answer is here.

http://stackoverflow.com/questions/679644/multiple-where-clause-in-linq

Dan
A: 

Yo could do it like this:

IQueryable<s> query= _dataContext.StatusUpdates;
foreach (var item in names)
{
    query = query.Where(p=>p.Username == item);
}
List<s> result = query.ToList();
Francisco
A: 

I think I mucked with some data types of yours but this should be close:

    var names = new List<string>();
    // populate names

    var updates = new List<StatusUpdate>();
    // populate updates

    var result = (from s in updates
          where names.Contains(s.ToString())
          select s).ToList();
Jaxidian
A: 

If you only need to check whether the Username property has some specified value, you can create a list of the values and then use method such as All or Any to check if some condition holds for any/all elements of the array.

Your example looks a bit suspicious though - the user name s.Username cannot be equal to multiple different strings. Did you want to check whether it is equal to any of the (specified) names? That could be written like this:

var friends = new[] { "friend1", "friend2", ... };
var result = 
  from s in dc.StatusUpdates 
  where friends.Any(fr => s.Username == fr)
  select s;

This returns all status updates such that the Username property is equal to any of the specified friend names (specified as an array, but you could use any IEnumerable<string>).

Tomas Petricek
sweet, thanks for this excellent answer mate, worked like a treat. I am a student and new to linq so just trying to get my head around some of the new syntax.I like the way you wrote this friends.Any(fr => s.Username == fr)... very easy to read and understand what is happening but not sure if i would have found it on my own:( thanks for the help
Dan
LINQ is quite flexible, especially when using extension methods explititly. Some good resources with more information are 101 LINQ samples: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx and a list of extension methods (such as `Any`): http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx
Tomas Petricek