我有以下情况:
public class Term{
private int _family;
public void setFamily(int family){
_family = family;
}
public int getFamily(){
return _family
}
}
public class Document{
private List<Term> _terms_in_document;
public void addTerm(Term t){
_terms_in_document.add(t);
}
}
在另一个班级......
Term t1 = new Term();
t1.setFamily(1);
Term t2 = new Term();
t2.setFamily(1);
Term t3 = new Term();
t3.setFamily(1);
Document d1 = new Document();
d1.addTerm(t1);
d1.addTerm(t2);
d1.addTerm(t3);
Term t4 = new Term();
t4.setFamily(1);
Term t5 = new Term();
t5.setFamily(2);
Term t6 = new Term();
t6.setFamily(3);
Document d2 = new Document();
d2.addTerm(t4);
d2.addTerm(t5);
d2.addTerm(t6);
我需要使用LINQ来获取包含具有最多不同系列的术语的文档。在我们的例子中,d2将首先出现,因为它的术语是1,2和3族。而d1必须是第二,因为它的所有术语都属于同一个族。到目前为止,我无法用linq做到这一点,我相信它可以在没有它的情况下完成,但它将是非常复杂且容易出错的代码。你能帮帮我..
答案 0 :(得分:1)
您可以使用GroupBy
按系列号对术语序列进行分组,然后在其上调用Count
以获取不同组的数量。
将所有这些内容放入OrderByDescending
来电,您将按照所有条款中不同家庭的数量订购文件。
答案 1 :(得分:1)
您应该使用属性。这就是他们的目的。此外,要使用LINQ,您需要一组文档。简而言之,您的代码可以转换为:
public class Term
{
public int Family { get; set; }
}
public class Document
{
private List<Term> terms = new List<Term>();
public List<Term> Terms { get { return terms; } set { terms = value; } }
}
internal class Program
{
private static void Main(string[] args)
{
Term t1 = new Term { Family = 1 }; // Object Initializer Syntax
Term t2 = new Term { Family = 1 };
Term t3 = new Term { Family = 1 };
Document d1 = new Document();
d1.Terms.Add(t1);
d1.Terms.Add(t2);
d1.Terms.Add(t3);
Term t4 = new Term { Family = 1 };
Term t5 = new Term { Family = 2 };
Term t6 = new Term { Family = 3 };
Document d2 = new Document();
d2.Terms.Add(t4);
d2.Terms.Add(t5);
d2.Terms.Add(t6);
List<Document> docs = new List<Document> {d1, d2};
}
}
然后你可以用:
进行计算var mostDistinctFamilies = docs.GroupBy(d => d.Terms.Select(t => t.Family).Distinct().Count())
.OrderByDescending(d => d.Count())
.First();