comparing two List<>

后端 未结 4 1087
栀梦
栀梦 2021-01-24 06:16

i have gridview control with a checkbox on it

When i hit on save button i able to find the checkbox which have been checked and i able to do it so far so good but the pr

相关标签:
4条回答
  • 2021-01-24 06:47

    You want something like this:

    var diff = selectedEmployee.Except(listFromDb, (a,b)=>a.id==b.id);
    foreach (Employee e in diff)
    {
        EmployeeService.SaveEmployee(e.Id, e.Name);
    }
    

    but you're awful short on particulars. What defines a change? How will match items in the list: by id? Can you be more exact with your requirements?

    0 讨论(0)
  • 2021-01-24 06:51

    Something like this should work:

    foreach (Employee item in MySelectedEmployee )
    {
       var currentEntry = listFromDB.FirstOrDefault( x => x.id == item.id);
       if(currentEntry == null || currentEntry.name!= item.name)
       {
         bool _flag = EmployeeService.SaveEmployee(item.Id, item.Name);
        ...
       }
    }
    

    Note that your initializations of List<Employee> are unnecessary, since you re-assign the variables on the next lines anyway.

    0 讨论(0)
  • 2021-01-24 07:04

    It sounds like what you need is set operations. You have a few choices:

    .NET 4.0 - HashSet<T>

    http://msdn.microsoft.com/en-us/library/bb359438.aspx

    .NET 3.5 - Linq extensions

    The Linq to Objects extensions contains some set operations like Intersect and Union. http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx

    .NET 2.0 - SetList<T>

    In 2.0 you'll need to hand-roll something like the following SetList class. http://csharptest.net/browse/src/Library/Collections/SetList.cs (online-help)

    To use SetList:

    SetList<Employee> listFromDB = new SetList<Employee>(EmployeeListFromDB);
    SetList<Employee> selectedEmployee = new SetList<Employee>(MySelectedEmployee);
    
    SetList<Employee> removed = listFromDB.SubtractSet(selectedEmployee);
    SetList<Employee> added = selectedEmployee.SubtractSet(listFromDB);
    

    Note: Employee must implement IComparable<Employee>, or you should write an IComparer<Employee> and provide it to the SetList constructor calls above.

    0 讨论(0)
  • 2021-01-24 07:12

    here is how you would do:

    List<Employee> found = EmployeeListFromDB.FindAll(a=>!selectedEmployee.Exists(b=>a.Id == b.Id));
    

    thats it...

    0 讨论(0)
提交回复
热议问题