.Distinct()子句不起作用C#MVC [英] .Distinct() clause not working c# MVC

查看:588
本文介绍了.Distinct()子句不起作用C#MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为许多视图填充一个下拉列表.相同的下拉菜单将用于我编写了Html Helper方法以生成下拉菜单的内容.

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;
    }

因此,在测试数据中,我执行了3批搜索结果.所以我想在下拉列表中看到3个批号.但是,我在SearchResults表中看到每个条目重复的批号,因此Distinct()子句似乎无法以所需的方式工作.

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.

我读到Distinct()对于对象很棘手,有人知道我可以用另一种方法实现这一点吗?

I've read that Distinct() is tricky with objects, does anyone know how I can achieve this another way?

推荐答案

有些实现,例如IEnumerable<obj>.DistinctBy(o => o.Prop),将通过特殊的Property支持.

There are some implementations like IEnumerable<obj>.DistinctBy(o => o.Prop) which will support distinct by a special Property.

以下内容也适用

list.GroupBy(l => l.Property).Select(group => group.First())

这篇关于.Distinct()子句不起作用C#MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆