惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
Recent Announcements
Recent Announcements
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The GitHub Blog
The GitHub Blog
MyScale Blog
MyScale Blog
爱范儿
爱范儿
GbyAI
GbyAI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
美团技术团队
Y
Y Combinator Blog
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
Martin Fowler
Martin Fowler
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
M
MIT News - Artificial intelligence
博客园 - Franky
V
Visual Studio Blog
I
InfoQ
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
博客园 - 司徒正美
L
LangChain Blog

博客园 - microsoft_xin

用户属性数据库设计:如何平衡固定信息与灵活扩展? mysql数据库千万级数据量是分库分表好还是数据归档好 MySQL 优化实战:为何 DELETE + IN 子查询性能不佳,而 JOIN 却能高效利用索引? git的还原提交和撤销提交可以帮你快速回滚提交和推送 java语法使用小技巧-保留两位小数-用group对list数据分组取和 java时间常用功能工具类 Navicat或DBeaver连接MySql提示错误 Unable to load authentication plugin ‘caching_sha2_password‘ 快速测试连接SQLServer数据库的方法 nlog使用小记(日志文件分割备份循环) IDEA常用快捷键 java中两个list集合取并集、交集和差集&对list数据进行对象属性筛选 Cron表达式及格式适用于各种调度服务quartz xxljob hangfire C#客户端实现域环境内Windows认证免密码自动身份认证登录 mysql-查看最近执行sql脚本 SharePoint安装 OpenID Connect、SAML、WS-Federation和/或OAuth2.0 SQLServer常用SQL脚本 使用VSTO创建修改和删除outlook会议加载项(二) 使用VSTO创建修改和删除outlook会议加载项(一)
.NET List常见操作之交集并集差集(转)
microsoft_xin · 2022-10-25 · via 博客园 - microsoft_xin

一、简单类型List的交集并集差集

1、先定义两个简单类型的List

List<int> listA = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
List<int> listB = new List<int>() { 1, 2, 3, 4, 9 };

2、取两个List的并集

var resultUnionList= listA.Union(listB).ToList();

执行结果如下:

3、取两个List的交集

var resultIntersectList = listA.Intersect(listB);

执行结果如下:

4、取两个List的差集,差集是指取在该集合中而不在另一集合中的所有的项

var resultExceptList = listA.Except(listB);

执行结果如下:

二、对象List集合的交集并集差集

1、先定义一个类

    /// <summary>
    /// 学生类
    /// </summary>
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
    }

2、定义两个List

            //LISTA
            List<Student> stuListA = new List<Student>();
            stuListA.Add(new Student
            {
                Name = "A1",
                Age = 10,
                Sex = "男"
            });
            stuListA.Add(new Student
            {
                Name = "A2",
                Age = 11,
                Sex = "男"
            });

            //LISTB
            List<Student> stuListB = new List<Student>();
            stuListB.Add(new Student
            {
                Name = "B1",
                Age = 10,
                Sex = "女"
            });
            stuListB.Add(new Student
            {
                Name = "B2",
                Age = 11,
                Sex = "男"
            });   

3、取上述两个list集合的并集

var result = stuListA.Union(stuListB).ToList();

4、取上述两个list集合的交集,应为是对象集合,可以根据一定规则 Func<TSource, bool> predicate限定那些属于交集

(1)取两个对象集合中对象名称一样的交集

var result = stuListA.Where(x => stuListB.Any(e => e.Name == x.Name)).ToList();

(2)取两个对象集合中对象名称、对象年龄、对象性别都一样的交集

var result = stuListA.Where(x => stuListB.Any(e => e.Name == x.Name && e.Age == x.Age && e.Sex == x.Sex)).ToList();

5、取上述两个list集合的差集,可以根据一定规则 Func<TSource, bool> predicate限定那些属于差集

(1)取差集,根据两个对象集合中对象名称一样的规则取差集

var result = stuListA.Where(x =>! stuListB.Any(e => e.Name == x.Name)).ToList();

(2)取差集,根据两个对象集合中对象名称、对象年龄、对象性别都一样的规则取差集

var result = stuListA.Where(x => !stuListB.Any(e => e.Name == x.Name && e.Age == x.Age && e.Sex == x.Sex)).ToList();

三、List<string>和List<int>互相转换

List<string> 转 List<int>

var list = (new[]{"1","2","3"}).ToList();
var newlist = list.Select<string,int>(x =>Convert.ToInt32(x));

List<int> 转List<string> 

List<int> list = new List<int>(new int[] { 1,2,3 } );
List<string> newList = list.ConvertAll<string>(x => x.ToString());

四、List排重

1、使用linq提供的Distinct方法

public class Test
{ 
     public int ID { get; set; }
     public string Name { get; set; }
}
public class TestMain
{
  public static void TestMothod()
  {
     List<Test> testList = new List<Test>();
      testList.Add(new Test { ID = 1, Name = "小名" });
      testList.Add(new Test { ID = 1, Name = "小红" });
      testList.Add(new Test { ID = 2, Name = "小名" });
      //通过使用默认的相等比较器对值进行比较返回序列中的非重复元素。
      List<Test> tempList = testList.Distinct<Test>().ToList();
   }
}

2、根据某个字段排除重复项

添加一个扩展排重扩展方法:

 public static class DistinctExtension
 {
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> seenKeys = new HashSet<TKey>();
        foreach (TSource element in source)
        {
            if (seenKeys.Add(keySelector(element)))
            {
                yield return element;
            }
        }
    }
 }

使用上述扩展方法:

public class TestMain
{
  public static void TestMothod()
   {
       List<Test> testList = new List<Test>();
       testList.Add(new Test { ID = 1, Name = "小名" });
       testList.Add(new Test { ID = 1, Name = "小红" });
       testList.Add(new Test { ID = 2, Name = "小名" });
       //根据某个字段排除重复项。
       List<Test> tempList = testList.DistinctBy(p => p.ID).ToList();
   }
}