user1015196
user1015196

Reputation: 637

Return List that Contains All Ids from an int list

I have a list of ids:

var IdList = new int[]{1, 2};

I also have a list of users:

var userList = new List<User>()
        {
            new User() {Id = 1, Name = "User1" },
            new User() {Id = 1, Name = "User2" },
            new User() {Id = 2, Name = "User2" },
            new User() {Id = 1, Name = "User3" },
            new User() {Id = 1, Name = "User4" },
            new User() {Id = 2, Name = "User4" }
        };

I want to get a list of users that must contain all the Ids from the IdList. So in this example I want to return User2 and User4. I've seen other subset examples that are just using Except and return boolean and even when adapting to my needs do not produce the correct results. I also saw one marked as duplicate (Similar Question) which is trying to do exactly this but did not agree that it was a duplicate and was never truly answered. I have attempted:

userList.Where(u => IdList.All(i => i == u.Id)).ToList();

that will not return anything.

Upvotes: 1

Views: 1272

Answers (3)

Magnetron
Magnetron

Reputation: 8553

Well, this is not elegant, but works:

List<string> result = new List<string>();
result = userList.Where(x => x.Id == IdList[0]).
          Select(x => x.Name).ToList();

for(int i =1; i<IdList.Count();i++)
{
    result = userList.Where(x => x.Id == IdList[i]).
          Select(x => x.Name).ToList().
          Intersect(result).ToList();
}

Upvotes: 0

hamid_reza hobab
hamid_reza hobab

Reputation: 929

Use Bellow 1Line linq code.

var q = userList.GroupBy(c => c.Name).Where(c => IdList.All(ccc => userList.Where(cc => cc.Name == c.Key).Any(cc => cc.Id == ccc))).ToList();

and this code return User2 and User4

Upvotes: 0

Shyju
Shyju

Reputation: 218732

Your question is a little confusing. You say you want to get a list of users that must contain all the Ids from the IdList and your expected output is User 2 and 4. That does not makes sense because your IdList has 1 and 2.

Also you have more than one record with Id 1. User1, User2 and User3 has same Id. What is the pattern to get one record from this ?

Assuming you do not have duplicate data and you want subset of items based on the items int eh idList, You can use LINQ Contains method.

var IdList = new int[]{1, 2};
var userList = new List<User>()
        {
            new User() {Id = 1, Name = "User1" },
            new User() {Id = 2, Name = "User2" },
            new User() {Id = 3, Name = "User3" },
            new User() {Id = 4, Name = "User4" }
        };
var subSet = userList.Where(d=>IdList.Contains(d.Id);

//subSet  will have records for  User1 and User2 

Upvotes: 1

Related Questions