w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
LINQ - groupBy with items in several Group

Try using HasFlag and GetValues to extract all the flags for a particular enum value:

var objs = new[] { new { a = MyEnum.first | MyEnum.second }, new
{ a = MyEnum.first }... };
var enumValues =

// first, use SelectMany to create a sequence with one instance of each
object for
// each flag value in it's a
var grouped = objs.SelectMany(
        o => enumValues.Where(flag => o.a.HasFlag(flag))
            .Select(v => new { o, flag })
    // then group by the extracted flag value
    // the element selector (t => t.o) gets us back to an IGrouping of
o's (dropping the extra flag property
    .GroupBy(t => t.flag, t => t.o);

 // finally, we can get sums by a as follows:
 var sumsByA = grouped.ToDictionary(g => g.Key, g => g.Sum(o =>

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.