如何使用 linq 返回过滤列表?

发布于 2024-10-25 18:09:37 字数 257 浏览 3 评论 0原文

我不确定我的标题是否正确,但 linq 应该吸引合适的专家来帮助标题并回答问题。

如果我有一个人员列表,如何返回减去“Dave”和“Jane”的 PeopleWrappers 列表?

查询现在看起来像这样:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小红帽 2024-11-01 18:09:44

您可以使用Where 来仅获取与条件匹配的元素:

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

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()
熟人话多 2024-11-01 18:09:43
People.Where( x => x.Name!="Dave" && x.Name!="Jane")
      .Select(t => new PeopleWrapper(t))
      .ToArray();

LINQ 有一个扩展方法列表,允许您进行筛选或项目(您已经使用 Select() 进行了这些操作)。在您的情况下,您可以使用 Where() 指定要让哪些元素通过,在您的示例中,所有姓名既不是 Dave 也不是 Jane 的人。

“Where”出现在前面有什么关系吗?
“选择”还是之后?

您通常希望尽快过滤,否则您将不得不迭代和/或投影您不想拥有的项目。

但从概念上讲,是的,您可以稍后放置 where() 过滤器但是,在您的情况下,您在使用 < 项目后正在处理 PeopleWrapper code>Select() - 由于 Where() 扩展方法使用此数据类型作为输入其条件,我认为这没有多大意义 - 您会过滤人员包装器,不是人。

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.

演出会有结束 2024-11-01 18:09:43
return People.Where(p => p.Name != "Dave" && p.Name != "Jane");
return People.Where(p => p.Name != "Dave" && p.Name != "Jane");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文