问题
I need to populate a dropdown list for for a number of views. The same drop down will be used to I wrote a Html Helper method to generate the contents of the dropdown.
public static List<SelectListItem> GetBatchNumbers(this HtmlHelper html)
{
List<SelectListItem> items = new List<SelectListItem>();
ModelContainer ctn = new ModelContainer();
var batchNumbers = ctn.SearchResults.OrderBy(x => x.BatchID).ToList();
foreach (var batch in batchNumbers.Distinct())
{
items.Add(new SelectListItem()
{
Text = batch.BatchID + "-" + batch.WebsiteName + "-" + batch.SourceName,
Value = batch.BatchID
});
}
return items;
}
So in my test data, I have performed 3 batches of search results. So I want to see 3 batch numbers in the drop down list. However, I am seeing a batch number repeated for each entry in the SearchResults table, so the Distinct() clause appears not to be working in the desired way.
I've read that Distinct() is tricky with objects, does anyone know how I can achieve this another way?
回答1:
There are some implementations like IEnumerable<obj>.DistinctBy(o => o.Prop)
which will support distinct by a special Property.
The following also works
list.GroupBy(l => l.Property).Select(group => group.First())
来源:https://stackoverflow.com/questions/16211909/distinct-clause-not-working-c-sharp-mvc