Maro
Maro

Reputation: 2629

Check if list of objects already exists in another list of objects

1- I I load list of Persons from CSV file and store it in list I load also list of Persons from db and store it in List

how can i get the users which they are in the csv file but not in the databse?

For example: DB has 5 Users (A,B,C,D,E) , CSV has 4 users (B,E,Q,P) the code should return list of users (Q,P)

public class Person
{
    public string UserName { get; set; }
    public int Age { get; set; }
}



 public class App
        {
            private IEnumerable<Person> usersDb;
            private IEnumerable<Person> usersCsv;

            public App(int age)
        {
             usersDb = GetUsersFromDb(age);
             usersCsv = GetUsersFromCsv(age);
        }

        public void AddMissingUsers()
        {
            var missingUsers = usersCsv.Where(x => !usersDb.Any(y => x.UserName.Trim().ToUpper().
                Equals(y.UserName.Trim().ToUpper()))); //I tried this one 
            // add to database
        }

    }

Additional question

Ps: I'm using entity framwork 6 is there a better way to perform the task shown in my code? instate of getting all users with from database then check if exists?

In the other hand, if i do the opposite and check each row in my csv file if exists in databse, this is also can be long operation since the file can contain many rows.

Upvotes: 1

Views: 120

Answers (2)

Venu prasad H S
Venu prasad H S

Reputation: 241

This should solve your problem, Change your Person class as follows,

public class Person : IEqualityComparer<Person>
    {
        public string UserName { get; set; }
        public int Age { get; set; }

        bool IEqualityComparer<Person>.Equals(Person x, Person y)
        {
            if (x.UserName == y.UserName)
                return true;
            return false;
        }

        int IEqualityComparer<Person>.GetHashCode(Person obj)
        {
            return base.GetHashCode();
        }
    }

Then change your query to,

Person p = new Person();
        var notInDBList = usersCsv.Except(usersDb, p).ToList();

Upvotes: 1

Kosala W
Kosala W

Reputation: 2143

You may be able to use Except in this case.

 var usersNotInDb = usersCsv.Except(usersDb).ToList();
 context.Users.AddRange(usersNotInDb);
 context.SaveChanges();

Upvotes: 1

Related Questions