过滤对象列表

Cod*_*nja 0 .net c# visual-studio-2010 c#-4.0

大家好,

我有一个对象列表ArrayList PList.该对象看起来像这样

Product 
{
    int ProductId,
    string ProductDescription,
    int StoreId 
    int supplierid
}
Run Code Online (Sandbox Code Playgroud)

我想将非重复的Products组合添加到另一个数组中

Product[] Parray
Run Code Online (Sandbox Code Playgroud)

例:

ArrayList Plist 具有 :

productid , productdescription, storeid, supplierid

1, "AB", 11 , 123
2, "CD", 24 ,454
1, "AB", 11 ,431
Run Code Online (Sandbox Code Playgroud)

我想要产品[] Parray

productid , productdescription, storeid, supplierid
1, "AB", 11 ,123
2, "CD", 24 , 454
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用哈希表来获取键值对,但在这种情况下我有3个键ProductId,description&storeid

这是我现在的代码:

private Types.Product[] LoadProducts()
{
    ArrayList PList = new ArrayList(); 
    // Business Logic , extracting values from xml using xpath
    //Loop though each xml node
    for (int j = 0; j < xmlprodlist.Count; j++)
    {
        //Business logic
        PList.Add(call another function here);
    }
    //What code here ??
    Types.Product[] PArray = (Types.Product[])PArrayList.ToArray(typeof(Types.Product));   
    return PArray;
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我我需要在这里添加什么代码的地方代码

slo*_*oth 5

您可以使用简单的方法GroupBy对数据进行分组,然后选择每个组的第一项:

Product[] Parray = PList.OfType<Product>()
                        .GroupBy(p => new {p.ProductId, p.ProductDescription, p.StoreId})
                        .Select(p => p.First())
                        .ToArray();
Run Code Online (Sandbox Code Playgroud)

请注意,您没有理由再使用ArrayList(甚至标记了您的问题C#4.0),更好地使用泛型List<T>类,这将使您的代码更安全,更易理解.

另一种方法是提供一个IEqualityComparer将所讨论的三个属性与Distinct方法进行比较的方法:

Product[] Parray = PList.OfType<Product>()
                        .Distinct(theIEqualityComparer)
                        .ToArray();
Run Code Online (Sandbox Code Playgroud)