【问题标题】:LINQ Comparison Between Two Child Property List Types?两个子属性列表类型之间的 LINQ 比较?
【发布时间】:2012-05-01 18:14:57
【问题描述】:

我已经看到了几个如何在 Linq 中使用 except 运算符和比较进行比较的示例,但它们似乎都显示了如何使用两个简单类型或一个简单类型和一个复杂类型来完成。我有两个不同类型的列表,我需要根据子属性选择一个结果,然后选择另一个属性匹配但 DateTime 较新的组。谁能帮我解决这个问题?

        public class Parent
        {
            public List<Child> ChildList;
        }

        public class Child
        {
            public string FoodChoice;
            public DateTime FoodPick;
        }


        public class Food
        {
            public string FoodName;
            public DateTime FoodPick;
        }

        public void FoodStuff
    {
       var parent = new Parent();
     var childList = new List<Child>();
childList.Add( new Child {FoodChoice="a",DateTime=..... 
childList.Add( new Child {FoodChoice="b",DateTime=..... 
childList.Add( new Child {FoodChoice="c",DateTime=..... 
parent.ChildList = childList;
        var foodList = new List<Food>();
        foodList.Add......
        var childrenWithNoMatchingFoodChoices = from ufu in Parent.ChildList where !Parent.ChildList.Contains ( foodList.FoodName )
        var childrenWithMatchingFoodChoicesButWithNewerFoodPick = from foo in Parent.ChildList where Parent.ChildList.FoodPick > foodList.FoodPick
    }

我想弄清楚如何为 childrenWithNoMatchingFoodChoices 获取 List&lt;Child&gt; 。 我想弄清楚如何为childrenWithMatchingFoodChoicesButWithNewerFoodPick 获得List&lt;Child&gt;

帮助?使用 .NET Framework 4.0。

谢谢。

【问题讨论】:

  • foodList 包含一个序列,不能像实例一样提供 FoodPick 属性。您必须说明要比较哪一个。
  • 我不确定您要的是什么。代替这种挥手的 C# 代码,您是否可以真正编写实际编译的 REAL C#。然后,添加一些断言之类的东西,这样我们就可以准确地看到是什么让你的代码工作了。基本上,给我们写一个单元测试,然后我们可以尝试让它通过。这个“.....”让我们(至少我)猜到你想做什么。

标签: linq comparison except


【解决方案1】:

要获取 FoodChoice 不在 foodList 中的儿童列表,我将使用以下查询:

var childrenNoMatch = parent.ChildList
                 .Where(ch => !foodList.Any(f => f.FoodName == ch.FoodChoice));

然后我会尝试以下方式:

    var childrenMatch = parent.ChildList.Except(childrenNoMatch);

    //childrenWithMatchingFoodChoicesButWithNewerFoodPick
    var moreRecent = from ch in childrenMatch
             let food = foodList.First(f => f.FoodName == ch.FoodChoice)
             where DateTime.Compare(ch.FoodPick, food.FoodPick) == 1
             select ch

虽然它没有经过测试。

【讨论】:

  • 更新后它现在应该可以编译了——起初我对课程中的所有食物感到很困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 2012-08-06
  • 2010-12-25
  • 2018-01-26
  • 1970-01-01
相关资源
最近更新 更多