0

I have a class and a list of it like this:

public class Person {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthday { get; set; }
}

// and my list is:
var persons = new List<Person>();
persons.add(/* add for example 20 person here */);

These persons may have duplicate FirstName and LastName. I want to select a subsequence of persons that all FirstName vs LastName are diferent. I mean my primary-key (in a relational db vision) is FirstName + LastName.

I know I can do this by iterating the list. But I'm asking a LINQ solution. Is there any one? May I select the specified subsequence by LINQ? Any idea please?

4

2 に答える 2

1

Create a Lookup<TKey, TElement> Class based on FirstName+LastName key and take only the first from each subcollection (as soon as you never said anything about it's rder or something) through Enumerable.ToLookup Method and Enumerable.Select Method:

var result = persons.ToLookup(p => string.Concat(p.FirstName, p.LastName))
                    .Select(l => l.First());
于 2012-11-28T08:31:02.683 に答える
1

You want only unique Persons? You can use Enumerable.GroupBy, then count each group:

var uniquePersons = persons 
                   .GroupBy(p => new { p.FirstName, p.LastName })
                   .Where(g => g.Count() == 1)
                   .Select(g => g.First());

Here's a demo: http://ideone.com/nsbyyI

于 2012-11-28T08:40:50.853 に答える