Possibly found function in Linq. Groupby with multiple fields

It seems that these two lines are doing the same thing. You can use plussign (+) instead of anonymous type.

var newlist1 = list.GroupBy(x => x.FIELD1 + x.FIELD2).Select(y => y.First());

var newlist2 = list.GroupBy(x => new {x.FIELD1, x.FIELD2}).Select(y => y.First());

      

Now my question is:

Is plussign (+) documented for GroupBy?

+3


source to share


1 answer


be careful: If, for example, x.FIELD1

and x.FIELD2

are properties of a type string, you are simply grouping by the result of the concatenation of the two ... which is probably not what you want. The same applies to other course types, but the example in lines is still:

Given Field1

= "ABC" and Field2

= "DEF", your grouping will be with the key "ABCDEF", right?

So what if you had Field1

= "AB" and Field2

= "CDEF"? Very different meanings, but your grouping will still be "ABCDEF" ...



You should stick to anonymous types for grouping (when used only within a method) or externally, a new class, structure, or tuple usage if necessary.

EDIT . One more note: after you have done GroupBy

(no projection), take a look at the key values ​​you get ... it should show you an example of what I mean.

+7


source







All Articles