gpt4 book ai didi

c# - 比较两种不同类型列表的项目 c#

转载 作者:太空狗 更新时间:2023-10-30 00:13:52 25 4
gpt4 key购买 nike

我想比较两个具有共同属性(名称)的不同列表。我已经尝试过 .Contains() 方法之类的方法,但这不起作用,因为我正在处理两个不同对象的列表。我已经尝试过以下问题的解决方案:

C# Compare Two Lists of Different Objects

C#, compare two different type of lists

compare different type of list in c#

但是这些解决方案不起作用,因为我的列表需要 Property 或 Animal 对象而不是“字符串”,这就是我遇到困难的地方。

我有两个类:

 public class Animal
{
public string Name = string.Empty;
public string XChromosome = string.Empty;
public string YChromosome = string.Empty;
}

public class Properties
{
public string Name = string.Empty;
public string Prop1 = string.Empty;
public string Prop2 = string.Empty;
}

两个列表如下所示:

List<Animal> = "name", "xposition", "yposition"
"name1", "xposition1", "yposition1" etc..

List<Properties> = "name", "prop1","prop2"
"name1", "prop3", "prop4" etc..

我想做的是,比较这两个列表,如果“名称”匹配,我想获取属于该名称的两个列表的内容。我也尝试过使用 HashSet 或字典,但这不是我想要的。

最佳答案

您可以 join Name 属性上的两个列表并作为匿名对象获取匹配项:

from a in animals
join p in properties on a.Name equals p.Name
select new {
a.Name,
a.XChromosome,
a.YChromosome,
p.Prop1,
p.Prop2
}

你可以在.NET Fiddle中自己尝试.


注意:如果您想获取动物信息而不管属性是否匹配,或者给定动物可以有多个匹配项,那么您需要使用 group join (check this fiddle 了解详情):

  from a in animals
join p in properties on a.Name equals p.Name into g
from p in g.DefaultIfEmpty()
select new {
a.Name,
a.XChromosome,
a.YChromosome,
Prop1 = p?.Prop1,
Prop2 = p?.Prop2
}

这将返回每对按名称连接的动物属性。如果未找到匹配的属性,则默认情况下 Prop1 和 Prop2 将具有空值(尽管您可以提供所需的任何默认值)。

关于c# - 比较两种不同类型列表的项目 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42621023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com