0

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 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

3
  • You mean you want to iterate over the collection (List<BusinessObject> I assume?) and find only those having different Column2 value? Commented Jul 19, 2011 at 13:01
  • Yes... I know there is a way to write it using the Distinct function... but I don't know how Commented Jul 19, 2011 at 13:12
  • Luckily Jon came to the rescue.. cheers! Commented Jul 19, 2011 at 14:01

3 Answers 3

2

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

2 Comments

ok.. this is great! not what if I don't know which Column the user is passing? What if I have e.ItemProperty is being passed (now e.ItemProperty can have either Column1, Column2, Column3 or Column4)?
and e.ItemProperty returns a String
0

Can use the pure LINQ distinct.

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

Where lbo is a collection of BusinessObjects.

Regards.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.