繁体   English   中英

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

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

从列表中获取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

分组的完美案例!

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