我有一个嵌套的linq
到sql
查询,用于填充treeview
。绑定到Title
时的第一个选择(treeview
字段)正确显示所有Titles
,但如果有多个出现,我希望它出现一次。我该如何解决这个问题?
我试过
}).Distinct().OrderBy(c => c.LineNumber)
}).Distinct();
完整查询
var results =
(from d in mContext.Docs
orderby d.Title ascending
join b in mContext.Base on d.DocId equals b.DocId
join h in mContext.ViewDocItems on b.BaseId equals h.BaseId
where h.ItemId == mGuid
select new
{
Id = d.DocId,
Title = d.Title,
ClassId = d.ClassId,
BaseHis =
(from c in d.Base
select new BaseHistory()
{
BaseId = c.BaseId,
Name = c.Title,
BaseFinal = c.Final.Value,
LineNumber = c.LineNumber.Value
ItemId = h.ItemId
}).Distinct().OrderBy(c => c.LineNumber)
});
foreach(var r in results)
{
var hist = new DocHistory()
{
Id = r.Id,
Title = r.Title,
ClassId = r.ClassId;
};
foreach(var h in r.BaseHis)
{
hist.BaseHis.Add(h);
}
mHistory.Add(hist);
}
答案 0 :(得分:4)
将Distinct()
替换为
.GroupBy(x => x.Name).Select(x => x.FirstOrDefault())
这意味着您在Name
(即Title
)上进行分组,然后获取每个组的第一个元素。
区别不起作用,因为,转换为SQL后,它会过滤掉所有每个值BaseId
,Title
等的唯一值的记录。