开发者

how do I return a filtered list using linq?

I'm not sure if my title is correct, but linq should pull the right experts in to help the title and answer the question.

If I have a list of People, how do I return a list of PeopleWrappers minus "Dave"开发者_如何学运维 and "Jane"?

query looks like this right now:

List<Person> People = CreatListofPersons();
People.Select(t => new PeopleWrapper(t)).ToArray();


People.Where( x => x.Name!="Dave" && x.Name!="Jane")
      .Select(t => new PeopleWrapper(t))
      .ToArray();

LINQ has a list of extension methods that allow you to filter or project (which you already to with Select()). In your case you can use Where() to specify which elements you want to let pass, in your example all persons whose name is neither Dave nor Jane.

does it matter if "Where" comes before "Select" or after?

You typically want to filter as soon as you can, otherwise you will have to iterate and/or project over items you don't want to have anyway.

Conceptually though, yes, you can put there where() filter later but in your case you are dealing with a PeopleWrapper after you project with Select() - since the Where() extension method is using this data type as input its condition I don't think it would make much sense - you would filter people wrappers, not persons.


return People.Where(p => p.Name != "Dave" && p.Name != "Jane");


You can use Where to get just the elements that match a condition:

People.Where(p => p.name != "Dave" && p.name != "Jane" ).Select(t => new PeopleWrapper(t)).ToArray()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜