我正在尝试使用 AsEnumerable
拉 Entity Framework DbContext
查询 IEnumerable<SelectListItem>
.这将用作填充 View 中下拉列表的模型属性。
但是,尽管有 Distinct()
,但每个查询都会返回重复的条目叫。
public IEnumerable<SelectListItem> StateCodeList { get; set; }
public IEnumerable<SelectListItem> DivCodeList { get; set; }
DivCodeList =
db.MarketingLookup.AsEnumerable().OrderBy(x => x.Division).Distinct().Select(x => new SelectListItem
{
Text = x.Division,
Value = x.Division
}).ToList();
StateCodeList =
db.MarketingLookup.AsEnumerable().OrderBy(x => x.State).Distinct().Select(x => new SelectListItem
{
Text = x.State,
Value = x.State
}).ToList();
最佳答案
为了使 Distinct
生效,您的序列必须包含实现 IEquatable
接口(interface)的类型的对象,如果该类型是自定义类型.
如前所述here :
Distinct returns distinct elements from a sequence by using the default equality comparer to compare values.
为了避免上述情况,一种解决方法是将序列的每个元素投影到 Division
然后生成 OrderBy
并调用 Distinct
:
var divisions = db.MarketingLookup.AsEnumerable()
.Select(ml=>ml.Division)
.OrderBy(division=>division)
.Distinct()
.Select(division => new SelectListItem
{
Text = division,
Value = division
}).ToList();
有关这方面的更多文档,请查看 here .
关于c# - .Distinct() 调用不过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28754846/