System.Linq中Union函数作用为将两个序列合并为一个不含重复数据序列,有两个重载函数,使用条件不相同
一、当IEnumerable<TSource>为简单类型(IEnumerable<string>、IEnumerable<int>等)
public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
注意:参数first、second要处理成为不重复序列
示例:
IEnumerable<int> intList1= new List<int> { 1, 2, 3, 4, 5, 6 };
IEnumerable<int> intList2 = new List<int> { 5, 6, 7, 8, 9, 0 };
IEnumerable<int> resultList = intList1.Union(intList2).OrderBy(i => i);
输出结果:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
二、当IEnumerable<TSource>为复杂类型(IEnumerable<T>)
public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer);
注意:参数first、second要处理成为不重复序列,参数comparer中IEqualityComparer为System.Collections.Generic中接口,接口是这样的
public interface IEqualityComparer<in T>
{
bool Equals(T x, T y);
int GetHashCode(T obj);
}
需要我们自己根据接口写实现类
public class EntityComparer : IEqualityComparer<T>
{
public bool Equals(T a, T b)
{
if (Object.ReferenceEquals(a, b)) return true;
if (Object.ReferenceEquals(a, null) || Object.ReferenceEquals(b, null))
return false;
return a.ID == b.ID && a.Name == b.Name && a.Grade == b.Grade;
}
public int GetHashCode(T a)
{
if (Object.ReferenceEquals(a, null)) return 0;
int hashName = a.Name == null ? 0 : a.Name.GetHashCode();
int hashCode = a.Grade.GetHashCode();
return hashName ^ hashCode;
}
}
写的时候要将T 替换
示例:
定义一个User实体类
public class User
{
public string ID { get; set; }
public string Name { get; set; }
public string Grade { get; set; }
}
定义一个接口实现类
public class EntityComparer : IEqualityComparer<User>
{
public bool Equals(User a, User b)
{
if (Object.ReferenceEquals(a, b)) return true;
if (Object.ReferenceEquals(a, null) || Object.ReferenceEquals(b, null))
return false;
return a.ID == b.ID && a.Name == b.Name && a.Grade == b.Grade;
}
public int GetHashCode(User a)
{
if (Object.ReferenceEquals(a, null)) return 0;
int hashName = a.Name == null ? 0 : a.Name.GetHashCode();
int hashCode = a.Grade.GetHashCode();
return hashName ^ hashCode;
}
}
IEnumerable<User> userList1= new List<User> { new User { ID = "0003", Name = "张三", Grade = "高三" }, new User { ID = "0002", Name = "王二", Grade = "高三" } };
IEnumerable<User> userList2= new List<User> { new User { ID = "0003", Name = "张三", Grade = "高三" }, new User { ID = "0004", Name = "李四", Grade = "高二" } };
IEqualityComparer<User> EC= new EntityComparer();
IEnumerable<User> resultList = userList1.Union(userList2, EC).OrderByDescending(u => u.ID);
输出结果:
ID = "0004", Name = "李四", Grade = "高二"
ID = "0003", Name = "张三", Grade = "高三"
ID = "0002", Name = "王二", Grade = "高三"
注意:
当需要将两个实体序列合并时,若实现第一个重载函数,得到序列会合并但会有重复值
网友评论