我需要迭代 Linq 从字典返回的列表。
但是,如果我使用 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.
如有任何帮助,我们将不胜感激。
最佳答案
不太确定你的数据结构,但你能做到吗:
var t = dict.Where(x => x.Key.Item1 == 50 || Math.Abs(x.Key.Item1 - 80) < 20)
.SelectMany(x => x.Value)
.ToList();
最终,如果您有嵌套的集合,SelectMany
基本上将许多集合合并为一个。因此,对于每个字典的集合,它会将它们展平为一个,而不是返回 IEnumerable
。对于每个元素,它将它们作为一个很好的集合返回:)
MSDN 上的示例非常好,并解释了对象的集合,每个对象都有自己的 List<T>
.所以基本上当我们做 SelectMany
它将众多的集合扁平化为一个我们可以Select
来自。
其他资源
关于c# - 如何使用 Linq 和 C# 迭代从字典返回的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33203010/