I'm trying to get distinct values for a dropdownlist, but when using the following syntax, it brings me back all the rows.
Can someone please inform me how to get a distinct value set with the correct syntax?
IEnumerable<SelectListItem> ldidList = _db.TrafficHits.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.ldid
}).Distinct();
If you want to achieve the distinct values for a specific field in the list, you can use the following two methods: 1 Using GroupBy and Select functions#N#In this approach, you need to use two LINQ functions i.e. GroupBy and Select to... 2 Using Select and Distinct functions More ...
The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values. SELECT DISTINCT column1, column2, ...
The problem with your current code is that Distinct will use the default comparer for SelectListItem. You will need to provide a custom comparer like this:-
LINQ DistinctBy () on a Property If you need a distinct list based on one or more properties, you can the following code: List bookList = GetBooks().DistinctBy(book => new { book.BookID, book.Title }); Using GroupBy and Select on a Property
The problem with your current code is that Distinct
will use the default comparer for SelectListItem
. You will need to provide a custom comparer like this:-
public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
public bool Equals(SelectListItem x, SelectListItem y)
{
return x.Text == y.Text && x.Value == y.Value;
}
public int GetHashCode(SelectListItem item)
{
int hashText = item.Text == null ? 0 : item.Text.GetHashCode();
int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
return hashText ^ hashValue;
}
}
Then you can use it like this:-
IEnumerable<SelectListItem> ldidList = _db.TrafficHits.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.ldid
}).Distinct(new SelectListItemComparer());
You can use the group by, then you select the first element per group :
IEnumerable<SelectListItem> ldidList = _db.TrafficHits
.GroupBy(t => t.Id)
.Select(g => g.First())
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.ldid
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With