1

I have a list of users as given below:

List<User> users = new List<User>();

users.Add(new User(){ UserId = "11", City = "London" });
users.Add(new User(){ UserId = "12", City = "London" });
users.Add(new User(){ UserId = "12", City = "London" });
users.Add(new User(){ UserId = "11", City = "Newyork" });
users.Add(new User(){ UserId = "14", City = "Virginia" });

Here, I want to get distinct UserIDs those have similar City by C# lambda expression

So, in above case I should get a List<string> which will only contains UserId = 12 item because UserId is same and city is also same for both the item.

Could you please let me know how would I do this by C# lambda code.

Thanks in advance.

nunu
  • 3,184
  • 10
  • 43
  • 58
  • possible duplicate of [C# lambda get distinct list of value conditionally](http://stackoverflow.com/questions/12176389/c-sharp-lambda-get-distinct-list-of-value-conditionally) – L.B Aug 29 '12 at 12:19
  • 1
    -1 for first asking [*"I want to get distinct UserIDs those have different City"*](http://stackoverflow.com/questions/12176389/c-sharp-lambda-get-distinct-list-of-value-conditionally) and then without showing any effort asking *"I want to get distinct UserIDs those have similar City"* – L.B Aug 29 '12 at 12:23

1 Answers1

2

Does your User type override Equals and GetHashCode appropriately? If so, it's as simple as:

var duplicated = users.GroupBy(x => x)
                      .Where(g => g.Count() > 1)
                      .Select(g => g.Key.UserId);

If not, you should probably consider overriding Equals and GetHashCode, or you could just use an anonymous type:

var duplicated = users.GroupBy(x => new { x.UserId, x.City })
                      .Where(g => g.Count() > 1)
                      .Select(g => g.Key.UserId);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194