views:

42

answers:

1

Hi,

I have the following List:

1: true; 
2: false;    
2: true;   
3: false;   
3: false;  
3: false;

I want a LINQ query to get a collection as the following:

key, OR operation between the grouped items, for example:

2: false | true  = true

The result must be:

1: true   
2: true   
3: false

Thanks in advance

+3  A: 
// my sample data
var list = new[] {
    new {key = 1, value = true},
    new {key = 2, value = false},
    new {key = 2, value = true},
    new {key = 3, value = false},
    new {key = 3, value = false},
    new {key = 3, value = false},
};
// the actual code
var groups = from pair in list
          group pair by pair.key into grp
          orderby grp.Key
          select new {
              grp.Key,
              Value = grp.Aggregate(false, (x, y) => x || y.value)
          };
// display the result
foreach (var grp in groups)
{
    Console.WriteLine("{0}: {1}", grp.Key, grp.Value);
}

Note you could also use Any to do the aggregate, with the advantage that it will short-circuit sooner:

      select new { grp.Key, Value = grp.Any(y => y.value) };
Marc Gravell