简体   繁体   English

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

[英]how to write this into linq to object query?

from a list, which got 3 attributes I want to return a new list of that class where attribut1 recurrence in the list equals X 从列表中获取3个属性我想返回该类的新列表,其中列表中的attribut1重复等于X

for an example this; 举个例子;

1,a,b 1,A,B
1,c,d 1,C,d
1,e,f 1,E,F
2,a,b 2,A,B
2,c,d 2,C,d
3,a,b 3,A,B
3,c,d 3,C,d
3,e,f 3,E,F
4,a,b 4,A,B
5,a,b 5,A,B
5,c,d 5,C,d
5,e,f 5,E,F
6,a,b 6,A,B
6,e,f 6,E,F

where X = 1 would return that list 其中X = 1将返回该列表

4,a,b 4,A,B

where X = 2 would return that list 其中X = 2将返回该列表

2,a,b 2,A,B
2,c,d 2,C,d
6,a,b 6,A,B
6,e,f 6,E,F

where X = 3 would return that list 其中X = 3将返回该列表

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

Perfect case for grouping! 分组的完美案例!

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);
seq.Where(l => seq.Count(i => i.attrib1 == l.attrib1) == X);
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);
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM