开发者

Return array of Property from Object Collection

开发者 https://www.devze.com 2023-03-21 15:25 出处:网络
I have a class with this structure: public class BusinessObject { public int Column1 { get; set; } public int Column2 { get; set; }

I have a class with this structure:

public class BusinessObject
{
    public int Column1 { get; set; }
    public int Column2 { get; set; }
    public string Column3 { get; set; }
    public int Column4 { get; set; }   
}

and I have a collection of objects of this type call BusinessObjectCollection. If I want an array of values that are distinct for only Column2... what must I do?

What if I dont know the property开发者_如何学C that I need... so if i have ColumnTitle as a String... and whatever the value of ColumnTitle... I want the distinct values for that property


Assuming you want the result to be an IEnumerable<BusinessObject>, so that Column2 is only used for implementing distinctness, there are two options:

  • Implement IEqualityComparer<BusinessObject> in a way which uses Column2, and pass that into Distinct
  • Use DistinctBy from MoreLINQ:

    var distinct = original.DistinctBy(x => x.Column2);
    

Obviously the second is simpler, but it does require an extra library (or copying just the code for DistinctBy).


This is the type of stuff that makes me really appreciate LINQ:

int[] distinctColumn2 = (from x in BusinessObjectCollection select x.Column2).Distinct().ToArray();


Can use the pure LINQ distinct.

var result = (from bo in lbo select bo.Column2).Distinct();

Where lbo is a collection of BusinessObjects.

Regards.

0

精彩评论

暂无评论...
验证码 换一张
取 消