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/

10-13 08:39