LINQ to Object对象的属性约束集合

时间:2016-05-07 06:57:14

标签: c# .net linq

我有一个包含6列的表,每列代表一个object,因此每个表行都是6个对象的集合,每个对象都有一个属性color

如何选择行中单个颜色不超过4个对象的所有行?

例如:

obj1.color=red, obj2.color=green, obj3.color=blue, obj4.color=green, obj5.color=blue, obj6.color=green

2 个答案:

答案 0 :(得分:2)

构造一个包含行中所有对象的数组。然后按颜色分组并检查所有组中是否包含多于4个项目。

var rows = tbl.Where(x =>
    new[]
    {
        x.obj1,
        x.obj2,
        x.obj3,
        x.obj4,
        x.obj5,
        x.obj6
    }
        .GroupBy(y => y.color)
        .All(g => g.Count() < 4));

答案 1 :(得分:1)

这是一个linqpad示例,说明如何使其发挥作用:

// sample table
var table = new[] { 
    new {c1="blue", c2="red", c3="green"},
    new {c1="blue", c2="blue", c3="blue"},      
    new {c1="blue", c2="red", c3="green"},
    new {c1="red", c2="red", c3="red"},
    };  

table.Where(row => (
    new[] {row.c1, row.c2, row.c3}) // transform rows to array of vals
                .GroupBy(r => r) // group the vals
                .Any(r => r.Count() == 3)) // filter the groups
    .Dump(description: "I love LINQPad!");