c# - 如何在linq中比较两个不区分大小写的复杂对象

标签 c# linq case-sensitive

我必须列出对象。所以我需要比较这些对象并从“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"

enter image description here enter image description here

最佳答案

要使用自定义比较策略比较 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/

相关文章:

c# regex - 从类文件 (.cs) 中选择类属性名称、方法名称和字段

.net正则表达式性能考虑: Use (partial or global) case-insensitive matching or explicit character groups?

python - Python 正则表达式如何忽略模式的一部分而不是整个表达式中的大小写?

c# - 如何以编程方式创建 Translate Storyboard动画 UWP?

c# - 在控制台应用程序中将范围 ({) 写入字符串

c# - "callback dispatcher"组件需要更好的设计

c# - linq to sql语法不同但应该得到相同的结果

C# 单元测试异步错误

linq - 使用 Linq 插入新记录时如何获取 SQL 命令文本?

Tomcat 和 Railo 迁移需要不区分大小写