










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 };
var resultUnionList= listA.Union(listB).ToList();
执行结果如下:

var resultIntersectList = listA.Intersect(listB);
执行结果如下:

var resultExceptList = listA.Except(listB);
执行结果如下:

/// <summary>
/// 学生类
/// </summary>
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
//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 = "男"
});
var result = stuListA.Union(stuListB).ToList();
(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();
(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>
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());
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();
}
}
添加一个扩展排重扩展方法:
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();
}
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。