Linq query correct way

I want a list of people who share the same first Name, but have birth year either before 1960 or after 1970.

It is just a practice query, i was working with intersect, through which i was getting only name, but what if i wanted the whole object of person.

I tried this one, which is working.

using Chapter01Samples;

var contacts = Contact.SampleData();
var callLog = CallLog.SampleData();

var result = from contact in contacts
             group contact by contact.FirstName into person
             where person.Any( c => c.DateOfBirth.Year > 1970) 
                               && person.Any(c => c.DateOfBirth.Year < 1960)
             select person;

But if there is a better query, i would like to know

EDIT: If there are 2 people named Adam, and one has birth year 58 and one has 72, then only i should receive both objects. Same name should exist in both the category.

Jon Skeet
people
quotationmark

I suspect you just need to reverse your where and group by clauses. Filter first, then group:

var result = from contact in contacts
             where contact.DateOfBirth.Year > 1970 ||
                   contact.DateOfBirth.Year < 1960
             group contact by contact.FirstName;

Note the change from && to ||, so that we only collect people who were born either before 1960 or after 1970.

If this isn't what you want, please give more details. In particular, if you're trying to find "people born before 1960 who share a first name with at least one person born after 1970" then I would split it into a few stages. First filter and group the users, so we have people born before 1960 grouped by first name, and people born before 1970 grouped by first name. You can then perform an inner join on those groups, and the result for any pair of groups with the same key (first name) is just the concatenation of the members of the two groups.

// No offence intended by these names...
var oldGroups = contacts.Where(contact => contact.DateOfBirth.Year < 1960)
                        .GroupBy(p => p.FirstName);
var youngGroups = contacts.Where(contact => contact.DateOfBirth.Year > 1970)
                          .GroupBy(p => p.FirstName);
var query = oldGroups.Join(youngGroups, og => og.Key, yg => yg.Key,
                           (og, yg) => og.Concat(yg));

people

See more on this question at Stackoverflow