it编程 > 编程语言 > Asp.net

C#使用Linq实现简单去重处理

26人参与 2025-02-20 Asp.net

一、示例代码

using system;
using system.collections.generic;
using system.linq;
 
public class program
{
    public static void main()
    {
        // 创建一些示例实体对象
        var people = new list<person>
        {
            new person { name = "alice", age = 30, city = "new york" },
            new person { name = "bob", age = 25, city = "los angeles" },
            new person { name = "alice", age = 30, city = "new york" },//重复的
            new person { name = "charlie", age = 35, city = "chicago" },
            new person { name = "alice", age = 28, city = "san francisco" }
        };
 
        // 1. 单字段去重
        var uniquenamefields = people.distinctby(p =>p.name).tolist();
        console.writeline("指定字段(name)去重结果,重复则保留第一条:");
        foreach (var person in uniquenamefields)
        {
            console.writeline($"name: {person.name}, age: {person.age}, city: {person.city}");
        }
 
        // 2. 多字段去重
        var uniquenameagefields = people.distinctby(p => new { p.name, p.age }).tolist();
        console.writeline("\n指定字段(name, age)去重结果,重复则保留第一条:");
        foreach (var person in uniquenameagefields)
        {
            console.writeline($"name: {person.name}, age: {person.age}, city: {person.city}");
        }
 
        //3.全字段去重
        // 通过 groupby 按 name 和 age 字段去重
        var uniquepeople = people.distinctby(p => new { p.name, p.age, p.city }).tolist();
        console.writeline("\n全字段去重:");
        foreach (var person in uniquepeople)
        {
            console.writeline($"name: {person.name}, age: {person.age}, city: {person.city}");
        }
    }
}
 
public class person
{
    public string name { get; set; }
    public int age { get; set; }
    public string city { get; set; }
}

二、示例输出

指定字段(name)去重结果,重复则保留第一条:
name: alice, age: 30, city: new york
name: bob, age: 25, city: los angeles
name: charlie, age: 35, city: chicago
 
指定字段(name, age)去重结果,重复则保留第一条:
name: alice, age: 30, city: new york
name: bob, age: 25, city: los angeles
name: charlie, age: 35, city: chicago
name: alice, age: 28, city: san francisco
 
全字段去重:
name: alice, age: 30, city: new york
name: bob, age: 25, city: los angeles
name: charlie, age: 35, city: chicago
name: alice, age: 28, city: san francisco

三、注意雷点

以下代码不能完成全字段去重,因为people是引用类型,distinct() 一般用于list<string>,list<int>这些值类型去重,而不涉及引用类型的字段比较。

people.distinct().tolist()

若需要全字段去重:1.使用dinstinctby语法,加上所有字段。2.使用标题四的封装方法(反射实现全字段去重)。

四、全字段去重封装方法

1.封装

/// <summary>
/// 通用的全字段去重方法
/// </summary>
/// <returns></returns>
public static ienumerable<t> distinctbyallfields<t>(ienumerable<t> items)
{
    // 获取 t 类型的所有字段值
    var properties = typeof(t).getproperties(bindingflags.public | bindingflags.instance);
 
    return items
        .groupby(item => string.join(",", properties.select(p => p.getvalue(item))))  // 按所有字段值连接生成唯一标识符
        .select(group => group.first());  // 取每组的第一个元素
}

2.示例

using system;
using system.collections.generic;
using system.linq;
using system.reflection;
 
public class program
{
    public static void main()
    {
        // 创建一些示例实体对象
        var people = new list<person>
        {
            new person { name = "alice", age = 30, city = "new york" },
            new person { name = "bob", age = 25, city = "los angeles" },
            new person { name = "alice", age = 30, city = "new york" },
            new person { name = "charlie", age = 35, city = "chicago" },
            new person { name = "alice", age = 28, city = "san francisco" }
        };
 
        // 调用封装的去重方法
        var uniquepeople = distinctbyallfields(people).tolist();
 
        console.writeline("根据所有字段去重的结果:");
        foreach (var person in uniquepeople)
        {
            console.writeline($"name: {person.name}, age: {person.age}, city: {person.city}");
        }
    }
 
    /// <summary>
    /// 通用的全字段去重方法
    /// </summary>
    /// <returns></returns>
    public static ienumerable<t> distinctbyallfields<t>(ienumerable<t> items)
    {
        // 获取 t 类型的所有字段值
        var properties = typeof(t).getproperties(bindingflags.public | bindingflags.instance);
 
        return items
            .groupby(item => string.join(",", properties.select(p => p.getvalue(item))))  // 按所有字段值连接生成唯一标识符
            .select(group => group.first());  // 取每组的第一个元素
    }
}
 
public class person
{
    public string name { get; set; }
    public int age { get; set; }
    public string city { get; set; }
}

以上就是c#使用linq实现简单去重处理的详细内容,更多关于c# linq去重的资料请关注代码网其它相关文章!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

C#使用NPOI实现将表格中数据导入Excel

02-18

C# string转unicode字符的实现

02-26

C#项目中引用Swagger的详细步骤和配置方式

02-27

C# swagger ui增加访问限制方式

02-27

WebView渲染异常导致闪退问题的解决方案

02-27

C#实现tostring转换成16进制的方法

02-27

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论