根据索引从列表中获取值作为一个组

时间:2014-05-15 06:54:17

标签: c# .net linq collections

我需要打印一个可能有多个值的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

因为我不想打印这个,而是想把它传递给另一个方法。所以我应该用一把钥匙来表示它的相应值。

1 个答案:

答案 0 :(得分:1)

只需按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);
}

或使用lookup

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

它将recordList中的项目按Data1属性值进行分组,并且对于组中的每个项目,它会在以下值中进行查找:

  (from m in recordList 
   where m.Data1 == x.Data1 
   select new MyData { Data2 = m.Data2, Data1 = m.Data1 }).First()

此查询的结果对于组中的所有项目都是相同的 - 它转到recordList找到与当前项目具有相同Data1的第一个项目(但不是相同的项目!)并创建其副本。因此,您最终会查找每个组中第一个项目的副本。