[英]Create a new list with values other than a property of the class of the list type
我有一个Customers
具有Id
和Name
属性的客户。 创建Customers
列表后,我想要一个没有重复名称的新customer
列表,即 Customers.Name 必须是唯一的。 我现在的output:
Gustavo
Gabriel
Mariza
Sandro
Gustavo
Gabriel
Lilian
Sandro
预计 Output:
Gustavo
Gabriel
Mariza
Sandro
Lilian
我试试这个,但我一直在犯与类型转换相关的错误:
using System;
using System.Collections.Generic;
using System.Linq;
namespace SelectDistinct
{
public class Program
{
static void Main(string[] args)
{
List<Customers> customers = new List<Customers>();
customers.Add(new Customers(0, "Gustavo"));
customers.Add(new Customers(0, "Gabriel"));
customers.Add(new Customers(0, "Mariza"));
customers.Add(new Customers(0, "Sandro"));
customers.Add(new Customers(0, "Gustavo"));
customers.Add(new Customers(0, "Gabriel"));
customers.Add(new Customers(0, "Lilian"));
customers.Add(new Customers(0, "Sandro"));
customers = customers.Select(x => x.Name.Distinct());
customers.ToList().ForEach(x =>
{
Console.WriteLine(x.ToString());
});
}
public class Customers
{
public int Id { get; set; }
public string Name { get; set; }
public Customers(int id, string name)
{
Id = id;
Name = name;
}
}
}
}
谁能帮忙?
使用GroupBy
给你一个预期的结果
var result = customers
.GroupBy(c => c.Name)
.Select(g => g.First())
.ToList();
result.ForEach(c => Console.WriteLine(c.Name));
Output 将是以下
Gustavo
Gabriel
Mariza
Sandro
Lilian
您发布的代码中有很多错误。
我注意到的第一件事是.Distinct()
的错误放置。 您已将它放在 select 内和Name
变量之后,这是不合逻辑的。
第二件事是,您正在尝试将类型为IEnumerable<char>
的customers.Select(x => x.Name.Distinct())
分配给类型为List<Customers>
的customers
变量。
现在,要实现您要查找的内容,您必须正确使用Distinct
扩展并将结果分配给正确的变量。
这是您的完整工作代码:
static void Main(string[] args)
{
List<Customers> customers = new List<Customers>();
customers.Add(new Customers(0, "Gustavo"));
customers.Add(new Customers(0, "Gabriel"));
customers.Add(new Customers(0, "Mariza"));
customers.Add(new Customers(0, "Sandro"));
customers.Add(new Customers(0, "Gustavo"));
customers.Add(new Customers(0, "Gabriel"));
customers.Add(new Customers(0, "Lilian"));
customers.Add(new Customers(0, "Sandro"));
IEnumerable<string> distinctNames = customers.Select(x=>x.Name).Distinct();
distinctNames.ToList().ForEach(x =>
{
Console.WriteLine(x.ToString());
});
Console.ReadKey();
}
public class Customers
{
public int Id { get; set; }
public string Name { get; set; }
public Customers(int id, string name)
{
Id = id;
Name = name;
}
}
这是 output:
Distinct
方法使用默认的相等比较器。
您需要重载Equals
和GetHashCode
方法才能正常工作。
public class Customers
{
// your code here
public override string ToString() => Id + " " + Name;
public override bool Equals(object obj)
{
return obj is Customers customers &&
Id == customers.Id &&
Name == customers.Name;
}
public override int GetHashCode()
{
int hashCode = -1919740922;
hashCode = hashCode * -1521134295 + Id.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name);
return hashCode;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.