Given MyEnum and a MyClass
[Flags] enum MyEnum { first = 1, second = 2, third = 4, forth = 8 } class MyClass { public MyEnum MyEnum; public uint Value; }
And some meanings
var mcs = new[] { new MyClass { MyEnum = MyEnum.first | MyEnum.third, Value = 10 }, new MyClass { MyEnum = MyEnum.second, Value = 20 }, new MyClass { MyEnum = MyEnum.first, Value = 100 }, };
This LINQ expression will return the sum of the values ββfor each enumeration value.
var ret = from p in Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>() select new { MyEnum = p, Sum = mcs.Where(q => q.MyEnum.HasFlag(p)).Sum(q => q.Value) };
Note that it will return a βstringβ even for MyEnum.fourth with a value of 0 .
The expression begins with enum values ββ( Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>() ), and then for each value it sums the mcs values ββthat have the same MyEnum ( mcs.Where(q => q.MyEnum.HasFlag(p)).Sum(q => q.Value) )
If you want to exclude enumeration values ββthat are not used:
var ret = from p in Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>() let temp = mcs.Where(q => q.MyEnum.HasFlag(p)).Select(q => q.Value).ToArray() where temp.Length > 0 select new { MyEnum = p, Sum = temp.Sum(q => q) };
An expression starts with enum values ββ( Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>() ), and then for each value it "stores" mcs values ββthat have the same MyEnum ( let temp = mcs.Where(q => q.MyEnum.HasFlag(p)).Select(q => q.Value).ToArray() ) in temp , skips temp which are empty ( where temp.Length > 0 ), and summarize the remaining temp ( select new { MyEnum = p, Sum = temp.Sum(q => q) } ). Note: if you use uint , you must use temp.Sum(q => q) , but with int you can use temp.Sum() (or you can use temp.Sum(q => q) ).
Another way is double from and group by
var ret = from p in Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>() from q in mcs where q.MyEnum.HasFlag(p) group q.Value by p into r select new { MyEnum = r.Key, Sum = r.Sum(p => p) };
This is probably equivalent to using SelectMany as suggested by ChaseMedallion (double from converted by the compiler to SelectMany )