110,530
社区成员
发帖
与我相关
我的任务
分享
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public override int GetHashCode()
{
return ($"{Name}_{Id}").GetHashCode();
}
}
static void Main(string[] args)
{
var list1 = new List<Product>();
var list2 = new List<Product>();
var dic1 = list1.ToDictionary(p => p, p => p);
var dic2 = list2.ToDictionary(p => p, p => p);
ExceptItems(list1, dic2);
ExceptItems(list2, dic1);
void ExceptItems(List<Product> listSrc, Dictionary<Product,Product> dicExcept)
{
var removeList = new List<Product>();
listSrc.ForEach(p =>
{
if (dicExcept.ContainsKey(p))
{
removeList.Add(p);
}
});
removeList.ForEach(p => listSrc.Remove(p));
}
}
public class list2
{
public int id;
public string name;
public list2(int d, string s)
{
id = d;
name = s;
}
}
public static List<list2> list2s = new List<list2>();
string[] list1 = new string[] { "A", "B", "C", "D" };
private void button1_Click(object sender, EventArgs e)
{
list2s.Add(new list2(1, "ABCDEFG"));
list2s.Add(new list2(2, "FFFFFFFFF"));
list2s.Add(new list2(3, "CCCCCCC"));
list2s.Add(new list2(4, "DFGHJUI"));
list2s.Add(new list2(5, "ZXZXZXZX"));
list2s.Add(new list2(6, "LOPIUYTC"));
// 全部符合
var query1 = list2s.Where(s => list1.All(t => s.name.Contains(t))).ToList();
// 包含
var query2 = list2s.Where(s => list1.All(t => s.name.Contains(t))).ToList();
// 不符合
var query3 = list2s.Where(s => list1.All(t => !s.name.Contains(t))).ToList();
// 不包含
var query4 = list2s.Where(s => list1.All(t => !s.name.Contains(t))).ToList();
}
static void Main(string[] args)
{
Random random = new Random();
List<Product> list1 = new List<Product>() {
new Product(1,"A"),
new Product(2,"B"),
new Product(3,"A"),
};
List<Product> list2 = new List<Product>() {
new Product(1,"A"),
new Product(2,"C"),
new Product(3,"D"),
};
for (int i = 0; i < 100 * 100; i ++)
{
list1.Add(new Product(random.Next(), "noname"));
list2.Add(new Product(random.Next(), "noname"));
}
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var list3 = list1.Except(list2, new ProductCompara());//移除list1中list2中存在的项
var list4 = list2.Except(list1, new ProductCompara());//移除list2中list1中存在的项
list3.Count();
list4.Count();
Console.WriteLine("耗时:" + stopwatch.ElapsedMilliseconds); // 我的机器耗时15355毫秒。
}
public int GetHashCode(Product obj)
{
return obj.Id; // Id是不错的HashCode(类似定位床铺的宿舍号)
}
static void Main(string[] args)
{
//...
Console.WriteLine("耗时:" + stopwatch.ElapsedMilliseconds); // 我的机器耗时6毫秒。
}
public int GetHashCode(Product obj)
{
return 0;
}