根据索引从列表中作为组获取值
本文关键字:获取 索引 列表 | 更新日期: 2023-09-27 18:03:31
我需要打印出一个可以有多个值的Key。但是我需要根据索引来打印这个。例如,如果我传递索引0,它应该检查A,然后打印出它的值。就像从1到n的东西。
即使我下面的例子是打印出第一个,因为我使用。first()。如何打印1到n。1个键有多个值。
recordList = new List<MyData>();
MyData add = new MyData { Data1 = "A", Data2 = "A is for Apple" };
recordList.Add(add);
MyData add1 = new MyData { Data1 = "A", Data2 = "B is for Ball" };
recordList.Add(add1);
MyData add2 = new MyData { Data1 = "A", Data2 = "C is for Cat" };
recordList.Add(add2);
MyData add3 = new MyData { Data1 = "A", Data2 = "D is for Doll" };
recordList.Add(add3);
MyData add4 = new MyData { Data1 = "B", Data2 = "A is for Apple" };
recordList.Add(add4);
MyData add5 = new MyData { Data1 = "B", Data2 = "B is for Ball" };
recordList.Add(add5);
MyData add6 = new MyData { Data1 = "B", Data2 = "C is for Cat" };
recordList.Add(add6);
MyData add7 = new MyData { Data1 = "B", Data2 = "D is for Doll" };
recordList.Add(add7);
var data = recordList.AsParallel().ToLookup(x => x.Data1, (x) =>
{
return (from m in recordList where m.Data1 == x.Data1 select new MyData { Data2 = m.Data2, Data1 = m.Data1 }).First();
});
var output = data["A"];
foreach(var print in output)
{
Console.WriteLine(print.Data1 + " "+ print.Data2);
}
我想达到的结果是:
A A is for Apple
B is for Ball
C is for Cat
D is for Doll
因为我想把它传递给另一个方法而不是打印出来。所以我应该有一个键和它对应的值
按Data1
属性对项目进行分组:
var groups = recordList.GroupBy(d => d.Data1);
然后,您将根据其Data1
值对项目进行分组。
foreach(var data1Group in groups)
{
Console.WriteLine(data1Group.Key); // group key A or B
foreach(var data in data1Group)
Console.WriteLine(data.Data2);
}
或者使用查找
var lookup = recordList.ToLookup(d => d.Data1, d => d.Data2);
// getting items for A
foreach(var data2 in lookup["A"])
Console.WriteLine(data2);
可以跳过投影查找项
var lookup = recordList.ToLookup(d => d.Data1);
在这种情况下,查找将类似于组,但使用按键索引访问。
你的代码有什么问题?让我们看看它是怎么做的
var data = recordList.ToLookup(x => x.Data1, (x) =>
{
return (from m in recordList
where m.Data1 == x.Data1
select new MyData { Data2 = m.Data2, Data1 = m.Data1 }).First();
});
按Data1
属性值对recordList
中的项进行分组,并对组中的每个项进行如下值查找:
(from m in recordList
where m.Data1 == x.Data1
select new MyData { Data2 = m.Data2, Data1 = m.Data1 }).First()
这个查询的结果对于组中的所有项目都是相同的-它转到recordList
,找到与当前项目具有相同Data1
的第一个项目(但不是相同的项目!)并创建其副本。因此,您最终得到的查找结果充满了每个组中第一项的副本。