【发布时间】:2021-04-07 11:05:27
【问题描述】:
我需要从整个国家集合中找到所有不同的项目(宗教),其中每个国家都有自己的项目(宗教)列表。这是我的对象类:
public class Country
{
public string Name { get; }
public List<string> Religions { get; }
public Country(string name, List<string> religions)
{
Name = name;
Religions = religions;
}
public static List<Country> GetCountries()
{
return new List<Country>()
{
new Country( "Venezuela", new List<string> { "Roman Catholic", "Protestant" } ),
new Country( "Peru", new List<string> { "Roman Catholic", "Evangelical" } ),
new Country( "Paraguay", new List<string> { "Roman Catholic", "Protestant" } ),
new Country( "Bolivia", new List<string> { "Roman Catholic", "Evangelical", "Protestant" } )
};
}
public override string ToString() =>
$"\n{Name} \nReligions: {string.Join(", ", Religions)}";
}
这是我的主要课程:
List<Country> countries = Country.GetCountries();
AllReligions(countries);
Console.ReadKey();
static void AllReligions(List<Country> countries)
{
var distinctReligions = countries
.Select(r => new { r.Religions })
.Distinct()
.ToList();
Console.WriteLine("Religions in South America:");
foreach (var rel in distinctReligions)
Console.WriteLine(rel);
}
我正在进行代码的第 5 次迭代,其中一个问题是我不知道错误发生在哪里 - 在我的 DISTINCT 函数内部或在我的打印输出函数内部。任何帮助将不胜感激。这是打印输出:
【问题讨论】:
-
两者。
Distinct()操作仅适用于匿名对象,而不适用于它们的内容。所有这些对象都是独一无二的,所以Distinct()什么都不做。Console.WriteLine作用于匿名对象,而不是Religions属性的内容。