【问题标题】:LINQ query returning null when comparing elements in two lists比较两个列表中的元素时,LINQ 查询返回 null
【发布时间】:2014-01-29 13:04:24
【问题描述】:

我正在检查两个列表中的元素并尝试添加到另一个列表:

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);
                }
            }
        }

假设我对 prodSubstitute 的测试 ID 是 1,5,4,2,3。 tempList id 中的元素是 1,2,3。当我通过 prodSubstitute 循环时,如果 prodSubstitute 不包含 tempList 中的 id,它应该添加到 prodIDList 中。但是,使用此 LINQ 查询,它只会一直返回 null 而不是 5,4。

有什么线索吗?提前致谢。

编辑

if (!prodIDList.Contains(prodSubstitute[count].id) && !(lstCategory.Where(x => x.Equals(categoryName)).Select(x => x).Count() >= 2))
                {
                    prodIDList.Add(prodSubstitute[count].id);
                    lstCategory.Add(categoryName);
                }

【问题讨论】:

  • 如果将 prodSubstitute.Any 更改为 prodSubstitute.Contains 会怎样?
  • 你的意思是 prodSubstitute.Contains(key) ?它向我显示了有关最佳重载方法的错误消息。包含无效参数
  • 我很抱歉,这是我的想法,这是错误的。 (虽然您可能可以使用比较器这样做,但这不是我的想法)
  • 没问题但还是非常感谢:)
  • 有什么意见吗?还没有解决

标签: c# asp.net linq


【解决方案1】:

这样的事情怎么样:

var prodIDList = tempList.Keys.Except(prodSubstitute.Select(p => (string)p.id);

这应该会产生tempList 中的内容和prodSubstitute 中的内容之间的差异,并将其放入字符串列表中。

注意:这应该替换您当前拥有的所有代码。

【讨论】:

  • 所以我应该把这条线放在foreach里面?如果我想执行一些 if else 语句,我需要这个列表的 for 循环吗?
  • @Carol,不,这就是你所需要的。你可以摆脱其余的。
  • @Carol:现在要注意的一件事是,您拥有的代码为prodSubstitute 生成了一个空列表。为此,或任何其他算法,要产生您正在寻找的东西显然需要在prodSubstitute 中。
  • 但是我还有一些其他的 if 语句代码。见编辑部分。因为我需要将记录限制为 2。所以我还需要列表的 for 循环吗?
  • @Carol:很抱歉,我不听。而且编辑也没有真正的帮助,因为有一些本地值没有被声明过——没有上下文。
猜你喜欢
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 2019-12-07
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多