using System;
using System.Collections.Generic;
using System.Linq;
namespace ListTest
{
class Program
{
protected static void Main(string[] args)
{
List<string> strs1 = new List<string> { "1", "2", "3", "1", "4" };
List<string> strs2 = new List<string> { "1", "0", "3", "1", "4" };
List<User> us = new List<User>();
us.Add(new User(Guid.Empty, "1111"));
us.Add(new User(Guid.NewGuid(), "2222"));
us.Add(new User(Guid.NewGuid(), "2222"));
us.Add(new User(Guid.NewGuid(), "3333"));
List<User> us2 = new List<User>();
us2.Add(new User(Guid.Empty, "1111"));
us2.Add(new User(Guid.Empty, "2222"));
us2.Add(new User(Guid.NewGuid(), "222423w5"));
//List去除重复
List<User> delegateList = us.Distinct(new Compare<User>(delegate(User x, User y) { if (null == x || null == y) return false; return x.UserName == y.UserName; })).ToList();
//List去重复
var strs = strs1.Except(strs2).ToList();
foreach (var item in delegateList)
{
Console.WriteLine(item.UserName);
}
//List取交集
strs = strs1.Intersect(strs2).ToList();
//foreach (var item in strs)
//{
// Console.WriteLine(item);
//}
//List取交集
List<User> delegateList2 = us.Intersect(us2, new Compare<User>(delegate(User x, User y) { if (null == x || null == y) return false; return x.UserName == y.UserName; })).ToList();
//foreach (var item in delegateList2)
//{
// Console.WriteLine(item.UserName);
//}
Console.ReadLine();
}
}
public class User
{
public User() { }
public User(Guid uid, string uname)
{
UserId = uid;
UserName = uname;
}
public Guid UserId { get; set; }
public String UserName { get; set; }
}
public delegate bool EqualsComparer<T>(T x, T y);
public class Compare<T> : IEqualityComparer<T>
{
private EqualsComparer<T> _equalsComparer;
public Compare(EqualsComparer<T> equalsComparer)
{
this._equalsComparer = equalsComparer;
}
public bool Equals(T x, T y)
{
if (null != this._equalsComparer)
return this._equalsComparer(x, y);
else
return false;
}
public int GetHashCode(T obj)
{ return obj.ToString().GetHashCode(); }
}
}
List(暂存)
最新推荐文章于 2023-06-04 23:29:04 发布