1

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.

1
  • sorry my mistake result is IEnumerable not List Commented Nov 23, 2010 at 21:19

3 Answers 3

4
private List<string> GetSearchResult(List<string> SourceList,
    string name, string[] items)
{
     return SourceList.Where(entry => entry.name == name 
         && items.Contains(entry.id))
}
Sign up to request clarification or add additional context in comments.

1 Comment

this will work, but if SourceList becomes a List<MyObject> you should think about implementing your own comparer. This will give you a way to customize your compare, for example X.Id == Y.Id.
2

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()))
}

Comments

1
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.

Comments

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.