Search code examples
linqcomparisonexcept

LINQ Comparison Between Two Child Property List Types?


I have seen several examples of how to compare in Linq using the Except operator and comparison, but they all seemed to show how it is done with two simple Types or one simple Type and one complex. I have two List of different types, I need to select a result based on a child property and then select another group where the properties match but a DateTime is newer. Can anyone help me through this?

        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
    }

I am trying to figure out how to get a List<Child> for childrenWithNoMatchingFoodChoices . I am trying to figure out how to get a List<Child> for childrenWithMatchingFoodChoicesButWithNewerFoodPick

Help? Using .NET Framework 4.0.

Thanks.


Solution

  • To get a list of children where FoodChoice is not on the foodList I would use this query:

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

    Then I would try something along these lines:

        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
    

    It's not tested though.