c# - How do I get a distinct list of list types -
this code (copy , paste linqpad if like)
var messageusers = new [] { new { msgid = 2, userid = 7 }, new { msgid = 2, userid = 8 }, new { msgid = 3, userid = 7 }, new { msgid = 3, userid = 8 }, new { msgid = 1, userid = 7 }, new { msgid = 1, userid = 8 }, new { msgid = 1, userid = 9 }}; messageusers .groupby (x => x.msgid, x => x.userid) .select (x => x.select (y => y)) .distinct() .dump();
the results {7,8}, {7,8}, {7,8,9}
what want {7,8}, {7,8,9}.
basically want remove duplicate lists. haven't tried think achieve creating comparer , passing distinct method. use in linq entities query without bringing thousands of rows client isn't option.
for clarification...i need return list> contents of each inner list distinct in comparison of other inner list.
the problem .distinct()
determines what's distinct based on gethashcode()
, equals()
implementation of underlying objects. in case, underlying object implements ienumerable<>
, uses default object
implementation methods--which based purely on whether objects occupy same space in memory. far can tell, sequences not distinct, though have same values in them.
how this?
messageusers .groupby (x => x.msgid, x => x.userid) .groupby(x => string.join(",", x)) .select(x => x.firstordefault()) .dump();
the idea group key represents combined value of elements in list. pass custom iequalitycomparer<>
distinct
method in original code, seems fair bit of effort trivial.
it's worth noting won't work if you're using linq entities or that.
update
to make list<list<int>>
, you'll need few .tolist()
s thrown in there:
messageusers .groupby (x => x.msgid, x => x.userid) .groupby(x => string.join(",", x)) .select(x => x.firstordefault().tolist()) .tolist() .dump();
but i'm frankly not sure why matters you.
Comments
Post a Comment