我已经看到了几个如何使用Except运算符和比较在Linq中进行比较的示例,但它们似乎都显示了如何使用两个简单类型或一个简单类型和一个复合体来完成它。我有两个不同类型的List,我需要根据子属性选择一个结果,然后选择属性匹配但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
}
我想知道如何为List<Child>
获取childrenWithNoMatchingFoodChoices
。
我想知道如何为List<Child>
childrenWithMatchingFoodChoicesButWithNewerFoodPick
帮助?使用.NET Framework 4.0。
感谢。
答案 0 :(得分: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
虽然没有经过测试。