.Distinct() clause not working c# MVC

依然范特西╮ 提交于 2019-12-11 19:18:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!