Linq to Sql: select single rows when ignoring specified columns

If I have a query / result, set the following ...

from t1 in table1
join t2 in table2 on t1.ID equals t2.ID
join t3 in table3 on t2.ID equals t3.ID
select new MyClass()
{
   ID = t1.ID,
   Name = t2.Name,
   Rank = t2.Rank,
   City = t3.City
}

ID | Name | City | Rank
01 | Test | Fake | 876
01 | Test | Fake | 755
02 | Blah | Fake | 765

Doing .Distinct () will return all 3 records, but what if I want the first and third record and don't want to remove columns from my result set? Is there a way to specify the columns to ignore when executing individual or explicitly include in a separate one so that I can do something like this ...

// pseudo code
.Distinct(o => o.Name.FirstOrDefault())

I think this can be done using a group, but it seems like it would be slow and messy, especially if I needed to group multiple columns so as not to exclude too many rows. Any ideas? Thank.

+3
source share
1 answer

, , Distinct. ( LINQ to Objects, .)

GroupBy, , First:

var query = from t1 in table1
            join t2 in table2 on t1.ID equals t2.ID
            join t3 in table3 on t2.ID equals t3.ID
            select new { t1.ID, t2.Name, t2.Rank, t3.City } into tuple
            group tuple by new { tuple.ID, tuple.Name, tuple.City } into grouping
            let first = grouping.First() // For convenience
            select new MyClass
            {
                ID = first.ID, City = first.City,
                Name = first.Name, Rank = first.Rank
            };

, - , , 876, , 755 .

, SQL, , , , .

+5

All Articles