我有一个项目列表,如下{One,Two,Three,One,Four,One,Five,Two,One},我需要一条查询语句,该语句基于唯一项目生成列表,因此返回的列表将是{One,Two,Three,Four,Five}。
var x = new string[] {"One", "Two", "Three", "One", "Four", "One", "Five", "Two", "One"}.ToList();
var distinct = x.Distinct();
使用distinct
List<string> l = new List<string>
{
"One","Two","Three","One","Four","One","Five","Two","One"
};
var rootcategories2 = l.Distinct();
除了Distinct,正如其他人提到的那样,您还可以使用HashSet:
List<string> distinct = new HashSet<string>(list).ToList();
我曾经遇到过类似的问题。我有一个importItems列表,其中包含customerName作为其中一个属性,并希望从原始列表中生成唯一客户列表。
我将原始列表传递给GenCustomers()...使用linq创建了一个itemCustomers唯一列表。然后我遍历该列表以创建新的Customer列表。
public static List<Customer> GenCustomers(List<ImportItem> importItems)
{
List<Customer> customers = new List<Customer>();
var itemCustomers = importItems.Select(o => new { o.CustomerName }).Distinct();
foreach (var item in itemCustomers)
{
customers.Add(new Customer() { CompanyName = item.CustomerName });
}
return customers;
}
感谢您的所有答案,我想我稍微错误地表达了我的问题。实际上,我有一个复杂的类,我希望基于类的特定成员进行比较(用于Distinct)。
class ComplexClass
{
public string Name{ get; set; }
public string DisplayName{ get; set; }
public int ComplexID{ get; set; }
}
List<ComplexClass> complexClassList = new List<ComplexClass>();
complexClassList.Add(new ComplexClass(){Name="1", DisplayName="One", ComplexID=1});
complexClassList.Add(new ComplexClass(){Name="2", DisplayName="Two", ComplexID=2});
complexClassList.Add(new ComplexClass(){Name="3", DisplayName="One", ComplexID=1});
// This doesn't produce a distinct list, since the comparison is Default
List<ComplexClass) uniqueList = complexClassList.Distinct();
class ComplexClassNameComparer : IEquatable<ComplexClass>
{
public override bool Equals(ComplexClass x, ComplexClass y)
{
return (x.To.DisplayName == y.To.DisplayName);
}
public override int GetHashCode(ComplexClass obj)
{
return obj.DisplayName.GetHashCode();
}
}
// This does produce a distinct list, since the comparison is specific
List<ComplexClass) uniqueList = Enumerable.Distinct(complexClassList , new ComplexClassNameComparer());
ComplexClassComparer
在Equals
和GetHashCode
的实现之间存在差异。确保返回值始终一致,目前并不明显。GetHashCode
应该返回obj.To.DisplayName.GetHashCode()
。 - Konrad Rudolph