I have one table which is looking like this
ID | UserID | UserEncryptValue |
---|---|---|
1 | 1 | abcd |
2 | 2 | 1234 |
3 | 3 | qwert |
4 | 1 | rstuv (Common value for user 1 and 2) |
5 | 2 | rstuv (Common value for user 1 and 2) |
6 | 2 | 78901 (Common value for user 2 and 3) |
7 | 3 | 78901 (Common value for user 2 and 3) |
8 | 1 | Hello123 (Common value for user 1,2 and 3) |
9 | 2 | Hello123 (Common value for user 1,2 and 3) |
10 | 3 | Hello123 (Common value for user 1,2 and 3) |
Now I want to find if user 1 and 2 or 1, 2 and 3 have common value or not with use of Linq.
CodePudding user response:
Assuming you're mapping that table to an actual object like 'UserData' like this:
public class UserData
{
public int Id { get; set; }
public int UserId { get; set; }
public string UserEncryptValue { get; set; }
}
You can get the common values like this (userData is a list of UserData and represents your data):
var searchId = 1;
var commonValues = userData.GroupBy(user => user.UserEncryptValue)
.Where(grp => grp.Count() > 1 && grp.Any(usr => usr.UserId == searchId))
.SelectMany(u => u);
This groups on the UserEncryptValue and only selects groups that have more than 1 value (has a match) and at least 1 of the user ids is equal to the searchId.
CodePudding user response:
Table.Where(n => Table.Any(o => !(o === n) && o.UserEncryptValue == n.UserEncryptValue)).Select(n => n.UserID)
Will return a collection of user id's for members of collection Table
where at least on other member of the table has the same value UserEncryptValue
but is not the same object
Learn LINQ to understand how this works and what you can do to tweak it.
CodePudding user response:
One way is to use GroupBy
. In this case you would group by UserEncryptValue
.
You can then examine each group and check which users are in each group.