[英]How to iterate a list returned from a Dictionary using Linq and C#
I need to iterate a list returned from a Dictionary by Linq. 我需要迭代Linq从Dictionary返回的列表。 But, if I use
ToList()
, it becomes a List of a List. 但是,如果我使用
ToList()
,它将成为列表的列表。
Dictionary<Tuple<double, double>, List<Tuple<double, double>>> dict = new Dictionary<Tuple<double,double>,List<Tuple<double,double>>>();
Random rnd = new Random();
for(int x =0; x < 3 ; ++x)
{
double a = rnd.NextDouble()*100;
double b = rnd.NextDouble()*100;
double c = Math.Ceiling(rnd.NextDouble()*100);
double d = Math.Ceiling(rnd.NextDouble()*100);
Tuple<double, double> tp = new Tuple<double, double>(c, d);
List<Tuple<double, double>> ll = new List<Tuple<double,double>>();
ll.Add(tp);
c = Math.Ceiling(rnd.NextDouble() * 100);
d = Math.Ceiling(rnd.NextDouble() * 100);
tp = new Tuple<double, double>(c, d);
ll.Add(tp);
dict.Add(new Tuple<double, double>(a, b), ll);
}
var t = dict.Where(x => x.Key.Item1 == 50 || Math.Abs(x.Key.Item1 - 80) < 20).Select(x => x.Value);
// if I used
var t = dict.Where(x => x.Key.Item1 == 50 || Math.Abs(x.Key.Item1 - 80) < 20).Select(x => x.Value).ToList();
// it became a list of list.
foreach(var u in t)
// here I cannot use u.item1 why?
// t is an Ienumerable of list<Tuple<double, double>>
// if I used foreach(var u in t.Tolist())
// it became a list of list.
Any help would be appreciated. 任何帮助,将不胜感激。
Not too sure on your data structure but can you do this: 不太确定您的数据结构,但是您可以这样做:
var t = dict.Where(x => x.Key.Item1 == 50 || Math.Abs(x.Key.Item1 - 80) < 20)
.SelectMany(x => x.Value)
.ToList();
Ultimately if you have collections nested, SelectMany
basically collapses many collections into one. 最终,如果您嵌套了集合,
SelectMany
基本上SelectMany
许多集合折叠为一个。 So in the case of your collections per Dictionary, it flattens them into one so instead of returning an IEnumerable
for each element, it returns them as one nice collection :) 因此,对于每个Dictionary的集合,它会将它们展平为一个,这样就不会为每个元素返回
IEnumerable
,而是将它们作为一个不错的集合返回:)
The example on MSDN is pretty nice, and explains how a collection of Objects, each with their own List<T>
. MSDN上的示例非常不错,并说明了如何收集对象,每个对象都有自己的
List<T>
。 So basically when we do the SelectMany
it flattens the numerous collections into one which we can Select
from. 因此,基本上,当我们执行
SelectMany
它会将众多集合SelectMany
为一个可以Select
集合。
Additional Resources 其他资源
Difference Between Select and SelectMany Select和SelectMany之间的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.