0

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

        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
    }

我试图弄清楚如何获得List<Child>for childrenWithNoMatchingFoodChoices。我想弄清楚如何获得List<Child>一个childrenWithMatchingFoodChoicesButWithNewerFoodPick

帮助?使用 .NET Framework 4.0。

谢谢。

4

1 回答 1

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

虽然它没有经过测试。

于 2012-05-01T18:23:24.420 回答