【问题标题】:Getting overlapping strings from two Lists of different classes从不同类的两个列表中获取重叠字符串
【发布时间】: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&lt;string&gt; animalNamesInButchering = butcheringMemos.Select(b =&gt; b.AnimalName).ToList();

标签: c# list for-loop


【解决方案1】:

使用 LINQ,您可以将所有内容组合成一个语句:

animalsToButcher = animals.Where(a => butcheringMemos.Select(m => m.AnimalName).Contains(a.Name)).ToList();

这将返回一个List&lt;Animal&gt; 对象,其中包含Name 与屠宰备忘录列表中的AnimalName 匹配的动物。那么你就不需要你的List&lt;string&gt; animalNamesInButchering,因为它在声明中。

【讨论】:

  • animalsToButcher 可能是有史以来最金属的变量名。
  • @Dortimer 这个问题有点残酷:'(
  • 我喜欢它在通用列表上返回 List !谢谢!
  • @Sly-Merc 这就是你要的!很高兴它对你有用。正如另一个答案中提到的,如果您需要不分大小写动物名称,您可以将m.AnimalNamea.Name 都设为.ToLower(),然后所有大小写都会匹配。目前,只会返回完全匹配的内容。
【解决方案2】:

您本质上想要获取名称出现在ButcheringMemo 列表中的所有此类动物。您可以使用 Linq Join() 如下所示(System.Linq 命名空间)

var data = butcheringMemos.Join(animals,
                                x => x.AnimalName,
                                y => y.Name,
                                (x, y) => new { Animal = x}).ToList();

【讨论】:

    【解决方案3】:

    您还可以使用稍微不同的 Linq 语法,对动物名称进行不区分大小写的比较:

    private static List<Animal> GetAnimalsToButcher()
    {
        List<ButcheringMemo> butcheringMemos = getAllButcheringMemos();
    
        return getAllAnimals()
            .Where(animal => butcheringMemos.Any(memo =>
                memo.AnimalName.Equals(animal.Name, StringComparison.OrdinalIgnoreCase)))
            .ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      • 2015-02-09
      • 2018-03-08
      相关资源
      最近更新 更多