How to get a separate list of list types

This is my code (copy and paste it into linqpad if you want)

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 I get are {7.8}, {7.8}, {7.8.9}

What I want is {7,8}, {7,8,9}.

Basically I want to remove duplicate lists. I have not tried this, but I think that perhaps I could achieve by creating a comparing and passing it to the Distinct method. However, I would like to end up using this in a Linq to Entities query without returning thousands of rows back to the client, so this is not a good option.

For further clarification ... I need to return a list> where the contents of each internal list are different compared to any other internal list.

+3
source share
2 answers

, .Distinct() , GetHashCode() Equals() . , IEnumerable<>, object , , . , , , .

?

messageUsers
    .GroupBy (x => x.MsgId, x => x.UserId)
    .GroupBy(x => string.Join(",", x))
    .Select(x => x.FirstOrDefault())
    .Dump();

, , . IEqualityComparer<> Distinct , - .

, , LINQ Entities - .

Update

List<List<int>>, .ToList():

messageUsers
    .GroupBy (x => x.MsgId, x => x.UserId)
    .GroupBy(x => string.Join(",", x))
    .Select(x => x.FirstOrDefault().ToList())
    .ToList()
    .Dump();

, .

+4

:

messageUsers
    .GroupBy (x => x.MsgId, y=>y.UserId)
    .Select (x => new HashSet<int>(x))
    .Distinct(HashSet<int>.CreateSetComparer())
    .Dump();

:

var messageUsers = new [] { 
    new { MsgId = 2, UserId = 7 },
    new { MsgId = 2, UserId = 8 },
    new { MsgId = 3, UserId = 8 },
    new { MsgId = 3, UserId = 7 },
    new { MsgId = 1, UserId = 7 },
    new { MsgId = 1, UserId = 8 },
    new { MsgId = 1, UserId = 9 }};

?

{7,8}, {7,8,9} {7,8}, {8,7}, {7,8,9}.

+1

All Articles