2

我有一个嵌套查询,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); 
}
4

1 回答 1

4

替换Distinct()

.GroupBy(x => x.Name).Select(x => x.FirstOrDefault())

这意味着您对Name(ie Title) 进行分组,然后获取每个组的第一个元素。

Distinct 不起作用,因为转换为 SQL 时,它会过滤掉所有具有唯一值的记录例如BaseId,Title等。

于 2013-05-08T19:11:50.940 回答