我们说我有以下代码:
private class AccountRecord : IEquatable<AccountRecord>, IComparable<AccountRecord>
{
public Guid accountid { get; set; }
public string accountnumber { get; set; }
public string name { get; set; }
public Guid ownerid { get; set; }
public string owneridtype { get; set; }
public int number { get; set; }
public string companyname { get; set; }
public AccountRecord(Guid accountid, string accountnumber, string name, Guid ownerid, string owneridtype, int number, string companyname)
{
this.accountid = accountid;
this.accountnumber = accountnumber;
this.name = name;
this.ownerid = ownerid;
this.owneridtype = owneridtype;
this.number = number;
this.companyname = companyname;
}
public bool Equals(AccountRecord other)
{
if(this.name.Equals(other.name) && this.number == other.number){
return true;
}
else
{
return false;
}
}
public int CompareTo(AccountRecord other)
{
if (this.number > other.number)
{
return 1;
}
else if (this.number < other.number)
{
return -1;
}
else
{
return 0;
}
}
}
在其他地方我有这些对象的列表:
private List<AccountRecord> accountRecords = new List<AccountRecord>();
我在列表中添加了几个对象:
accountRecords.Add(new AccountRecord(
Row.accountid,
Row.accountnumber,
name,
Row.ownerid,
Row.owneridtype,
number,
companyname));
然后,我会得到一个&#39; companyname&#39;的不同值列表。属性。
List<string> distinctCompanynames = accountRecords.Distinct(x => x.companyname).ToList<string>();
我希望获得一个具有最高&#39;号码的AccountRecord对象列表。每个不同的公司名称的属性&#39;属性。感谢我所做的工作,我可以使用嵌套for循环来完成这项工作,但考虑到C#处理的所有工具,我的整个方法似乎不是最好的方法。这个列表最终会变得非常大,而且这段代码会经常执行,所以我必须尽可能高效地执行此操作。我怎样才能比现有的方法更快/更好地做到这一点?
我目前的方法是:
我喜欢的方法是什么:
如果您有任何疑问,请告诉我。
答案 0 :(得分:1)
我还没有对此进行测试,但这应该可行:
from ac in accountRecords
group ac by ac.companyname into company
select new
{
Company = company.Key,
Number = company.OrderByDescending(g => g.number).FirstOrDefault()
}
更新:更仔细地阅读问题。它可以简化:
List<AccountRecord> highestRecords =
(from ac in accountRecords
group ac by ac.companyname into company
select company.OrderByDescending(g => g.number).FirstOrDefault())
.ToList();