如何从列表中获取不同的值

时间:2013-10-12 06:45:32

标签: entity-framework-4 linq-to-entities

我有一个从Linq到Entities查询生成的List。其中,我需要根据BibId获取唯一记录。我已尝试更改查询,但无法根据BibId获取唯一记录。

查询

aa.NewBibContentsModel = (from x in db.BibContents

                                      where (x.TagNo == "245" && x.NormValue == aa.CurrentTitle) || (x.TagNo == "020" && x.NormValue == aa.CurrentISBN) || (x.TagNo == "022" && x.NormValue == aa.CurrentISBN)
                                      select new
            {
                BibId = x.BibId,
                Title = (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == "245" orderby a.Id ascending select a.NormValue),
                //Tit = (from a in db.BibContents where a.BibId == line.BibId && a.TagNo == "245" && a.Sfld == "a" select a.NormValue).FirstOrDefault(),
                Author = (from a in db.BibContents where a.BibId == x.BibId && splitted.Contains(a.TagNo) && a.NormValue != null select a.TagNo).FirstOrDefault(),
                ISBN = (from a in db.BibContents where a.BibId == x.BibId && a.NormValue != null && (a.TagNo == "020" || a.TagNo == "022") orderby a.Id ascending select a.NormValue)
            }).AsEnumerable().Select(x => new BibContentsModel
            {
                BibId = x.BibId,
                Title = string.Join(" ", x.Title),
                Author = string.Join(" ", (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == x.Author orderby a.Id select a.NormValue)),
                ISBN = string.Join(" ", x.ISBN)
            }).ToList();

对此问题的任何帮助都将不胜感激。

由于

1 个答案:

答案 0 :(得分:0)

您要实现的目标是 Distinct By MoreLinq具有此功能。语法如下:

(from x in db.BibContentsNo == "022")
... // your query
}).AsEnumerable()
.DistinctBy(x => x.BibId) // <= MoreLinq

做什么是按BibId对记录进行分组,并取每组的第一个元素。

您可以将MoreLinq下载为NuGet包。