我试图描述的最好方式是“嵌套DistinctBy”。
假设我有一个对象集合,每个对象包含一个昵称集合。
class Person
{
public string Name { get; set; }
public int Priority { get; set; }
public string[] Nicknames { get; set; }
}
public class Program
{
public static void Main()
{
var People = new List<Person>
{
new Person { Name = "Steve", Priority = 4, Nicknames = new string[] { "Stevo", "Lefty", "Slim" }},
new Person { Name = "Karen", Priority = 6, Nicknames = new string[] { "Kary", "Birdie", "Snookie" }},
new Person { Name = "Molly", Priority = 3, Nicknames = new string[] { "Mol", "Lefty", "Dixie" }},
new Person { Name = "Greg", Priority = 5, Nicknames = new string[] { "G-man", "Chubs", "Skippy" }}
};
}
}
我想选择所有人,但要确保没有人选择与另一个人相同的昵称。Molly和Steve都分享昵称“Lefty”,所以我想过滤掉其中一个人。只有最高优先级的人应被包含在内。如果2个或多个人具有相同的最高优先级,则只需选择它们中的第一个人。因此,在这个例子中,我希望得到除Steve之外的所有人的IEnumerable。
编辑:这里有另一个例子,使用音乐专辑而不是人,可能更有意义。
class Album
{
string Name {get; set;}
int Priority {get;set;}
string[] Aliases {get; set;}
{
class Program
{
var NeilYoungAlbums = new List<Album>
{
new Person{ Name = "Harvest (Remastered)", Priority = 4, Aliases = new string[] { "Harvest (1972)", "Harvest (2012)"}},
new Person{ Name = "On The Beach", Priority = 6, Aliases = new string[] { "The Beach Album", "On The Beach (1974)"}},
new Person{ Name = "Harvest", Priority = 3, Aliases = new string[] { "Harvest (1972)"}},
new Person{ Name = "Freedom", Priority = 5, Aliases = new string[] { "Freedom (1989)"}}
};
}
这里的想法是展示他的唱片目录,但我们希望跳过准重复的内容。
4
,而 Molly 的优先级为3
。两者都使用 Lefty 作为昵称,但是选择了 Molly 而不是 Steve,因此我认为较低的数字意味着更高的优先级。 - Tobias Tengler