Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare two complex object without case sensitive in linq

I have to list object. so i need to compare these object and get satisfied list from "datActualItem" to the list. The list "datActualItem" items may be case sensitive but the list "datFiltItem" items all are small letter my code below.

 var datActualItem = (List<UserRoleListViewModel>)TempResult.ToList();
    var datFiltItem = ((List<UserRoleListViewModel>)usersDataSource.Data).ToList();

    var objnewm = new List<UserRoleListViewModel>();
            foreach (var item in datActualItem)
            {
                objnewm.Add(datActualItem.Where(s => s.Equals(datFiltItem)).FirstOrDefault());
            }

Note:- The array list item Firstname is "Sajith" other list is containing "sajith" so currently not checking due to this. I need to checking without case sensitive and to the add list from the "datActualItem"

enter image description here enter image description here

like image 456
Sajith Avatar asked Feb 06 '23 05:02

Sajith


1 Answers

To compare 2 lists with custom comparison strategy, you can create a class that implements IEqualityComparer<T>:

public class MyClassComparer : IEqualityComparer<UserRoleListViewModel>
{
    public bool Equals(UserRoleListViewModel x, UserRoleListViewModel y)
    {
        return x.ID == y.ID
            && x.FirstName.Equals(y.FirstName, StringComparison.CurrentCultureIgnoreCase)
            && x.LastName.Equals(y.LastName, StringComparison.CurrentCultureIgnoreCase);
         // continue to add all the properties needed in comparison
    }

    public int GetHashCode(MyClass obj)
    {
        StringComparer comparer = StringComparer.CurrentCultureIgnoreCase;

        int hash = 17;
        hash = hash * 31 + obj.ID.GetHashCode();
        hash = hash * 31 + (obj.FirstName == null ? 0 : comparer.GetHashCode(obj.FirstName));
        hash = hash * 31 + (obj.LastName == null ? 0 : comparer.GetHashCode(obj.LastName));
        // continue all fields

        return hash;
    }
}

Usage:

var list = actual.Except(expected, new MyClassComparer());

Another way would be to override equality of your own class UserRoleListViewModel but that affects everything and not just this Except method.

like image 115
Zein Makki Avatar answered Apr 26 '23 02:04

Zein Makki