我必须列出对象。所以我需要比较这些对象并从“datActualItem”到列表中获得满意的列表。列表“datActualItem”项目可能区分大小写,但列表“datFiltItem”项目都是小写字母我的代码如下。
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"
最佳答案
要使用自定义比较策略比较 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
方法。
关于c# - 如何在linq中比较两个不区分大小写的复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39324695/