2

I have a collection of objects which are: someDate someString

I need to select objects that are different by this two fields. And I can not select it as objects in collections - I need to create new ones.

Say:

01/01/2011 "One"

01/01/2011 "One"

01/01/2011 "One"

01/01/2011 "Two"

(I need to note - this four are different to each other)

And I need to get:

01/01/2011 "One"

01/01/2011 "Two"

How can I achieve it?

Thanks.

1
  • Your question is unclear, particularly: "And I can not select it as objects in collections - I need to create new ones." Commented Jul 27, 2011 at 11:09

1 Answer 1

5

Your question is fairly unclear, but it sounds like you either just need to use Distinct after a projection:

var distinctDatesAndNames = items.Select(x => new { x.Date, x.Name })
                                 .Distinct();

or you need to use something like DistinctBy from MoreLINQ:

var distinctItems = items.DistinctBy(x => new { x.Date, x.Name });

It would really help if you could clarify your question though.

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

2 Comments

After projection? My main problem is that I thought that "new" keyword will create an instance of anonymous object for EVERY object in incoming collection. How can Distinct() determine - which are different and which are not?
@Monochromie: Yes, it will create a new instance for each object - but then Distinct will use Equals and GetHashCode to find equal ones.

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.