简体   繁体   English

LINQ 选择嵌套列表上的表达式

[英]LINQ Select Expression on nested list

How would I go about looping through a nested list with Linq?我将如何使用 Linq 遍历嵌套列表?

I have a nested list which looks like this:我有一个嵌套列表,如下所示:

var bookings = new List<List<Booking>>();

Inside the Booking class are booking details, and such在 Booking 类中是预订详细信息,例如

I want to loop through each indivudal list and extract the list which is nested by using Linq, but I'm struggling to do it :(我想遍历每个单独的列表并提取使用 Linq 嵌套的列表,但我正在努力做到这一点:(

I'm not sure what method i should use with Linq, i've tried using SelectMany but i dont think I understand it well enough.我不确定我应该对 Linq 使用什么方法,我试过使用 SelectMany,但我认为我对它的理解不够好。

If you're trying to flatten the list with SelectMany :如果您尝试使用SelectMany使列表变平:

bookings.SelectMany((list) => list);

If you're trying to extract each individual list:如果您尝试提取每个单独的列表:

bookings.ForEach((list) => {
    // Do something with the nested list
});

If you're trying to filter the nested lists, but maintain those the lists:如果您尝试过滤嵌套列表,但要维护这些列表:

bookings.Select((list) => list.Where((item) => item.Price > 20));

And so on.等等。

SelectMany expects a function that turns each item in a list into a IEnumerable<T> and then flattens the resulting IEnumerable<T> of IEnumerable<T> s into a IEnumerable<T> . SelectMany期望匝的每个项目在列表成一个函数IEnumerable<T>然后变平所得到IEnumerable<T>IEnumerable<T> s转换为IEnumerable<T> By using SelectMany with an identity function (list) => list you're effectively doing nothing with each item in the list—they are already IEnumerable<T>'s and, as such, dont need any further transformation— SelectMany will then subsequently flatten the resulting IEnumerable<T> of IEnumerable<T> s.通过将SelectMany与标识函数(list) => list您实际上SelectMany (list) => list每个项目做任何事情——它们已经是IEnumerable<T>'s ,因此不需要任何进一步的转换——然后SelectMany将随后平坦化所得IEnumerable<T>IEnumerable<T>秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM