【发布时间】:2019-10-03 00:58:42
【问题描述】:
假设我有两个不同的课程:
class Animal
{
string Name {get; set;}
int Age {get; set;}
string Description {get; set;}
}
class ButcheringMemo
{
string ButcherShopName {get; set;}
DateTime ButcheringTime {get; set;}
string AnimalName {get; set;}
}
如果我有一个 Animal 列表和一个 ButcheringMemo 列表,那么在 ButcheringMemo 中创建 Animal 的 Name 显示为 AnimalName 的 Animal 产品列表的最佳方法是什么?
我的马虎方式如下:
List<Animal> animalsToButcher = new List<Animal>();
List<ButcheringMemo> butcheringMemos = getAllButcheringMemos();
List<string> animalNamesInButchering = new List<string>();
foreach (ButcheringMemo memo in butcheringMemos)
{
animalNamesInButchering.Add(memo.AnimalName);
}
List<Animal> animals = getAllAnimals();
foreach (Animal animal in animals)
{
bool isIn = false;
foreach (string name in animalNamesInButchering)
{
if (animal.Name == name)
isIn = true;
}
if (!isIn)
{
animalsToButcher.Add(animal);
}
}
return animalsToButcher;
我觉得肯定有比在 for 循环中包含 for 循环更好的方法。
【问题讨论】:
-
您可能想在我们的姊妹网站Code Review 上发布关于工作代码的反馈。
-
List<string> animalNamesInButchering = butcheringMemos.Select(b => b.AnimalName).ToList();