Linq'S Distinct() on a Particular Property

LINQ's Distinct() on a particular property

EDIT: This is now part of MoreLINQ.

What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}

So to find the distinct values using just the Id property, you could use:

var query = people.DistinctBy(p => p.Id);

And to use multiple properties, you can use anonymous types, which implement equality appropriately:

var query = people.DistinctBy(p => new { p.Id, p.Name });

Untested, but it should work (and it now at least compiles).

It assumes the default comparer for the keys though - if you want to pass in an equality comparer, just pass it on to the HashSet constructor.

Distinct by property of class with LINQ

You can use grouping, and get the first car from each group:

List<Car> distinct =
cars
.GroupBy(car => car.CarCode)
.Select(g => g.First())
.ToList();

Distinct in LINQ-C#

The 3 records that you see at debug time is your existing list. I think all that you've missed is an assignment.

List<LinqTest> myList = new List<LinqTest>();
myList.Add(new LinqTest() { id = 1, value = "a" });
myList.Add(new LinqTest() { id = 1, value = "b" });
myList.Add(new LinqTest() { id = 2, value = "c" });
// not sure why new {m.id} was used in this context
List<int> distinctList = myList.Select(m => m.id).Distinct().ToList();

Linq to get distinct property

Rewrite your GetHashCode() function:

public int GetHashCode(MY_DATA_TABLE obj)
{
return obj.CODE.GetHashCode();
}

Rule is, that both Equals and GetHashCode() should check the same properties, and you checking just Code in Equals() and whiole object in GetHashCode()

Use LINQ to select distinct properties in Lists of Lists

You can do that like this, directly using the public DateCollection member:

var unique = master.DateCollection
.SelectMany(x => x.Data.Select(d => d.Value))
.Distinct()
.ToList();

The key being SelectMany to "flatten" the selection.



Related Topics



Leave a reply



Submit