Click here to Skip to main content
15,890,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have users list from that list how to remove all records except few records in c#.


The below code is removing all records and count is 0.

Scenario


list: 1,2,3,4,5,6

require only : 3,4,5

What I have tried:

I Have tried with the below code and getting count 0

class Program
    {
        static void Main(string[] args)
        {
            List<Userdetails> allDetails = new List<Userdetails>() { new Userdetails() { UserId=1,UserName="A"},
            new Userdetails() { UserId=2,UserName="B"},
            new Userdetails() { UserId=3,UserName="C"},
            new Userdetails() { UserId=4,UserName="D"},
            new Userdetails() { UserId=5,UserName="E"},
            new Userdetails() { UserId=6,UserName="F"}};

            List<int> newIds = new List<int>();
            newIds.Add(2);
            newIds.Add(3);
            

            foreach (int userId in newIds)
            {
                var result = allDetails.Where(u => u.UserId == userId).ToList();
            }

        }
    }
    public class Userdetails { public int UserId { get; set; } public string UserName { get; set; } }
Posted
Updated 10-Jun-19 8:10am

1 solution

Try:
C#
List<Userdetails> allDetails = new List<Userdetails>() {
    new Userdetails() { UserId=1,UserName="A"},
    new Userdetails() { UserId=2,UserName="B"},
    new Userdetails() { UserId=3,UserName="C"},
    new Userdetails() { UserId=4,UserName="D"},
    new Userdetails() { UserId=5,UserName="E"},
    new Userdetails() { UserId=6,UserName="F"}};

List<int> newIds = new List<int>();
newIds.Add(2);
newIds.Add(3);
List<Userdetails> result = allDetails.Where(ud => newIds.Contains(ud.UserId)).ToList();
 
Share this answer
 
Comments
DGKumar 10-Jun-19 14:28pm    
Excellent Thank you very much Griff this should help to minimize my code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900