如何检查列表A不包含列表B中的任何元素

时间:2018-07-12 09:18:37

标签: c# list linq contains

我想返回一个列表对象,其中 productFromSqls 中任何元素的值有何不同。 我尝试这样做,但不起作用。

var result = productFromSqls.Where(
            x => !productFromApis.Any(y => y.id == x.idshop))
            .ToList();

示例应返回ProductFromSql id = 1和id = 2

模型

public class ProductFromSql
{
    public string idEshop { get; set; }
    public string active { get; set; }

    public string code { get; set; }
    public string amount { get; set; }
    public string description { get; set; }

}


public class ProductFromApi
{
    public string id { get; set; }
    public string active { get; set; }

    public string code { get; set; }
    public string amount { get; set; }
    public string description { get; set; }
    public string createDate { get; set; }
    public string updated_at { get; set; }
    public string  man_code  { get; set; }
}

列表

public static void NotEquals()
{

    var productFromSqls = new List<ProductFromSql> {
            new ProductFromSql {idEshop="1", active="0",code="2dw",amount="22",description="testowy opis"},
            new ProductFromSql {idEshop="2", active="1",code="kk34",amount="11",description="testowy opis 2"},
            new ProductFromSql {idEshop="3", active="0",code="2323",amount="22",description="testowy opis 3"} 
    };

    var productFromApis = new List<ProductFromApi> {
            new ProductFromApi {id="1", active="1",code="2dw",amount="22",description="testowy opis",createDate="20180312",updated_at="20170419",man_code="AA2"},
            new ProductFromApi {id="2", active="1",code="kk34",amount="33",description="testowy opis 2",createDate="20180322",updated_at="20170412",man_code="AA4"},
            new ProductFromApi {id="3", active="0",code="2323",amount="22",description="testowy opis 3",createDate="20180311",updated_at="20170402",man_code="BA4"}
    };

}

2 个答案:

答案 0 :(得分:0)

您需要添加一个方法,该方法将比较对象中所有对象的所有元素,这两个类都是相同的

List<ProductFromSql> Filtered = new List<ProductFromSql>();

productFromSqls.ForEach(x => productFromApis.ForEach(ele => 
                             {
                                if(!AreObjectsEqual(x, ele) && !Filtered.Any(ele => ele.id == x.id)) 
                                    Filtered.Add(x);  
                             }));


public bool AreObjectsEqual(ProductFromSql obj1, ProductFromApi obj2)
{
   return (obj1.id == obj2.idEshop && obj1.active == obj2.active)//......) //Add other properties of your class which are common in both in ........
}

答案 1 :(得分:0)

您需要添加所有要比较的属性。

<local:DataGridListBoxColumn   Binding="{Binding M_Name,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" ListItems="{Binding DataContext.stud, Source={x:Reference studAccess}}"  Width="100"/>