【发布时间】:2021-08-29 12:10:38
【问题描述】:
我在一个列表中有一个列表。我需要两个将 sub_List 的两个属性与第三个列表进行比较。
类:
public class Human
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
public List<Clothing> clothings { get; set; }
}
public class Clothing
{
public string ClothingID{ get; set; }
public string Garment{ get; set; }
public string Color{ get; set; }
}
public class CurrentClothes
{
public string Garment{ get; set; }
public string Color{ get; set; }
}
伪代码:
public List<Human> humans = new List<Human>()
{
new Human
{
FirstName="Karl",
LastName="Karlson"
clothings=new List<Clothing>()
{
new Clothing
{
ClothingID="1",
Garment="T-Shirt",
Color="pink"
},
new Clothing
{
ClothingID="11",
Garment="Pant",
Color="white"
},
new Clothing
{
ClothingID="111",
Garment="Shoes",
Color="black"
}
}
},
new Human
{
FirstName="Paula",
LastName="Paulson"
clothings=new List<Clothing>()
{
new Clothing
{
ClothingID="2",
Garment="T-Shirt",
Color="red"
},
new Clothing
{
ClothingID="22",
Garment="Pant",
Color="blue"
},
new Clothing
{
ClothingID="222"
Garment="Shoes",
Color="black"
}
}
}
};
public List<CurrentClothes> currentclothes = new List<CurrentClothes>()
{
new CurrentClothes
{
Garment="Pant",
Color="blue"
},
new CurrentClothes
{
Garment="T-Shirt",
Color="red"
},
new CurrentClothes
{
Garment="Shoes",
Color="black"
}
}
var human = humans.Where(x=>x.clothings.Equals(currentClothes));
问题是,我如何比较当前的衣服是否与某些人的衣服相匹配。有没有 Linq 选项?
我添加了一个示例。在此示例中,有两个人。卡尔和保拉。现在的衣服是确定的。现在我想要人类如何匹配当前的衣服。在这种情况下是宝拉。
【问题讨论】:
-
你能给我们提供预期输出的样本数据吗?对我来说,这实际上很不清楚
-
是
Enumerable.Any你在找什么? -
你叫什么“比较”你如何定义它们是否相等?也许你应该实现
IEquatable -
您应该重写 Clothing 类的 Equals 方法。请参阅此处的文档,您将知道如何将其与 CurrentClothes 进行比较。 docs.microsoft.com/en-us/dotnet/api/… 。通过这种方式,您可以重新定义您的标准,了解如何始终比较这两个类并定义您的平等标准
-
@Zinov 您能否在我的示例中提供一个代码示例如何覆盖 equal 方法并使用 ist 从列表中获取正确的人?
标签: c# list linq ienumerable