C# 比较两个列表中的元素时返回null的LINQ查询
我正在检查两个列表中的元素并尝试添加到另一个列表中:C# 比较两个列表中的元素时返回null的LINQ查询,c#,asp.net,linq,C#,Asp.net,Linq,我正在检查两个列表中的元素并尝试添加到另一个列表中: List<ProductPacking> prodSubstitute = new List<ProductPacking>(); tempList = new Dictionary<string, string>(); List<string> prodIDList = new List<string>(); for (int count = 0; count < prodS
List<ProductPacking> prodSubstitute = new List<ProductPacking>();
tempList = new Dictionary<string, string>();
List<string> prodIDList = new List<string>();
for (int count = 0; count < prodSubstitute.Count; count++)
{
foreach (string key in tempList.Keys)
{
if (!prodSubstitute.Any(i => i.id == key))
{
prodIDList.Add(prodSubstitute[count].id);
}
}
}
像这样的怎么样:
var prodIDList = tempList.Keys.Except(prodSubstitute.Select(p => (string)p.id);
这将产生templast
中的内容与prodSubstitute
中的内容之间的差异,并将其放入字符串列表中
注意:这将替换您当前拥有的所有代码。如果您将prodSubstitute.Any更改为prodSubstitute.Contains,该怎么办?您是指prodSubstitute.Contains(键)?它向我显示了一条关于最佳重载方法的错误消息。Contains有无效的参数。我很抱歉,这是我头脑中的错误。(虽然你可以用比较器这样做,但这不是我想的)没问题,但还是非常感谢:)有什么评论吗?还没解决,所以我应该把这条线放在沙发里?如果我想执行一些if-else语句,我需要为这个列表创建一个for循环?@Carol,不,这就是你所需要的。你可以去掉剩下的。@Carol:现在需要注意的一点是,你的代码为
prodSubstitute
生成了一个空列表。对于这一点,或者任何其他算法,要产生您正在寻找的东西,显然需要在prodSubstitute
中。见编辑部分。因为我需要将记录限制为2。那么,我还需要列表中的for循环吗?@Carol:对不起,我不明白。而且编辑也没有真正的帮助,因为有些本地值一次都没有声明过——只是没有上下文。
var prodIDList = tempList.Keys.Except(prodSubstitute.Select(p => (string)p.id);