How to compare two complex objects without case sensitivity in linq

I need to list an object. so I need to compare this object and get a list with a list of "datActualItem". The elements of the datActualItem list may be case sensitive, but all the elements of the datFiltItem list are the small letter of 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 list element of the Firstname array is "Sajith", the other list contains "sajith", so it is not currently checked because of this. I need to check case insensitive and add a list from "datActualItem"

enter image description here enter image description here

+4
source share
2 answers

2 , , 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;
    }
}

:

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

UserRoleListViewModel, , Except.

+4

StringComparison.OrdinalIgnoreCase

bool equals = string.Equals("Test", "test", StringComparison.OrdinalIgnoreCase);

Except, , IEqualityComparer (. ) string.Equals("Test", "test", StringComparison.OrdinalIgnoreCase) . Becasue Linq , .

GetHashCode Equals ( ), .

+3

Source: https://habr.com/ru/post/1653637/


All Articles