如何将此写入linq到对象查询?

时间:2010-02-24 20:32:03

标签: c# .net vb.net linq

从列表中获得3个属性 我想返回该类的新列表,其中列表中的attribut1重复等于X

以此为例;

  

1,A,B
  1,C,d
  1,E,F
  2,A,B
  2,C,d
  3,A,B
  3,C,d
  3,E,F
  4,A,B
  5,A,B
  5,C,d
  5,E,F
  6,A,B
  6,E,F

其中X = 1将返回该列表

  

4,A,B

其中X = 2将返回该列表

  

2,A,B
  2,C,d
  6,A,B
  6,e,f

其中X = 3将返回该列表

  

1,A,B
  1,C,d
  1,E,F
  3,A,B
  3,C,d
  3,E,F
  5,A,B
  5,C,d
  5,e,f

3 个答案:

答案 0 :(得分:3)

分组的完美案例!

var groups = list.GroupBy(s => s.Attribute1);
var recur_1 = groups.Where(g => g.Count() == 1).SelectMany(s => s);
var recur_2 = groups.Where(g => g.Count() == 2).SelectMany(s => s);
var recur_3 = groups.Where(g => g.Count() == 3).SelectMany(s => s);

答案 1 :(得分:1)

seq.Where(l => seq.Count(i => i.attrib1 == l.attrib1) == X);

答案 2 :(得分:0)

public static void Test()
{
    var list = new[]
                {
                    new {p1 = 1, p2 = 'a', p3 = 'b'},
                    new {p1 = 1, p2 = 'c', p3 = 'd'},
                    new {p1 = 1, p2 = 'e', p3 = 'f'},
                    new {p1 = 2, p2 = 'a', p3 = 'b'},
                    new {p1 = 2, p2 = 'c', p3 = 'd'},
                    new {p1 = 3, p2 = 'a', p3 = 'b'},
                    new {p1 = 3, p2 = 'c', p3 = 'd'},
                    new {p1 = 3, p2 = 'e', p3 = 'f'},
                    new {p1 = 4, p2 = 'a', p3 = 'b'},
                    new {p1 = 5, p2 = 'a', p3 = 'b'},
                    new {p1 = 5, p2 = 'c', p3 = 'd'},
                    new {p1 = 5, p2 = 'e', p3 = 'f'},
                    new {p1 = 6, p2 = 'a', p3 = 'b'},
                    new {p1 = 6, p2 = 'e', p3 = 'f'}


                };

    for (int i = 1; i <= 3; i++)
    {
        var items = from p in list
                 group p by p.p1
                 into g
                    where g.Count() == i
                    from gi in g
                    select gi;

        Console.WriteLine();
        Console.WriteLine("For " + i);
        Console.WriteLine();
        foreach (var x in items)
        {
            Console.WriteLine("{0},{1},{2}", x.p1, x.p2, x.p3);
        }

    }
}