一、使用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(); } }
二、根据某个字段排除重复项
添加一个扩展排重扩展方法:
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(); } }