[英]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.