gpt4 book ai didi

c# - 检查 List 元素是否包含具有特定属性值的项目

转载 作者:行者123 更新时间:2023-11-30 15:36:51 26 4
gpt4 key购买 nike

public class Item
{
public List<int> val { get; set; }
public double support { get; set; }
}

我声明变量:

List<Item> t = new List<Item>();
t.Add(new Item(){val = new List<int>(){1,2,3};support=.1);
var b = new Item();
b.val = t[0].val;
b.support=t[0].support;
t.Contain(b) // return false???

我正在尝试使用 linq

t.Any(a=>a.val==b.val) // I'm get error Expression cannot contain lambda expressions

最佳答案

我想到了 3 种可能性:

你可以实现 IEquatable<T> :

public class Item: IEquatable<Item>
{
public List<int> val { get; set; }
public double support { get; set; }

public bool Equals(Item other)
{
return
this.support == other.support &&
this.val.SequenceEqual(other.val);
}
}

现在t.Contains(b)将返回 true。


如果您无法修改 Item类你可以写一个自定义 EqualityComparer :

public class ItemEqualityComparer : IEqualityComparer<Item>
{
private ItemEqualityComparer()
{
}

public static IEqualityComparer<Item> Instance
{
get
{
return new ItemEqualityComparer();
}
}

public bool Equals(Item x, Item y)
{
return
x.support == y.support &&
x.val.SequenceEqual(y.val);
}

public int GetHashCode(Item obj)
{
int hash = 27;
hash += (13 * hash) + obj.support.GetHashCode();
foreach (var item in obj.val)
{
hash += (13 * hash) + item.GetHashCode();
}
return hash;
}
}

然后 t.Contains(b)还将返回 true .


或者,如果您更喜欢天真地做:

List<Item> t = new List<Item>();
t.Add(new Item { val = new List<int>(){1,2,3}, support=.1 });

var b = new Item();
b.val = t[0].val;
b.support = t[0].support;

bool equals = t.All(item => item.support == b.support && item.val.SequenceEqual(b.val));
Console.WriteLine(equals);

关于c# - 检查 List<T> 元素是否包含具有特定属性值的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13334321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com