fireBand
fireBand

Reputation: 957

LINQ query to query a list with array members

I am trying to query a list using LINQ.

The query statement contains entries which should match items from an array.

In other words get entries from SourceList which match any one of the items from the items array. Example:

private List<string> GetSearchResult(List<string> SourceList,
    string name, string[] items)
{
     IEnumerable<string> QueryList = SourceList.Where
         (entry => enrty.name == name && entry.id == <any item from items>)
}

I thought of building a query string looping though the items array. I wanted to know if there is an efficient way of doing this.

Upvotes: 1

Views: 4337

Answers (3)

as-cii
as-cii

Reputation: 13039

private List<string> GetSearchResult(List<string> SourceList,
    string name, string[] items)
{
     return SourceList.Where(entry => entry.name == name 
         && items.Contains(entry.id))
}

Upvotes: 4

Mike Caron
Mike Caron

Reputation: 14561

private List<string> GetSearchResult(List<string> SourceList,string name, string[] items)
{
     return SourceList.Where(entry => entry.name == name && items.Contains(entry.id)).ToList();
}

That should do it.

Upvotes: 1

Adam Driscoll
Adam Driscoll

Reputation: 9483

What about:

private List<string> GetSearchResult(List<string> SourceList,string name, string[] items)
{
     List<string> QueryList = SourceList.Where
                     (entry => enrty.name == name && items.Any(m => m == entry.id.ToString()))
}

Upvotes: 2

Related Questions