【问题标题】:Linq query a List of objects containing a list of objectLinq 查询包含对象列表的对象列表
【发布时间】:2015-12-30 15:43:15
【问题描述】:

我有一个名为 crepes 的 foo 列表。我想返回 foo bar.doritos == "coolRanch"

class foo
{
    List<bar> item;
    string candy;
    string beer;
}

class bar
{
    string doritos;
    string usb;
}

var item = crepes.item.Where(x => x.doritos == "coolRanch").FirstOrDefault();

从其他线程,我拼凑了上面的 linq 查询,但 crepes.item 抛出一个错误。 “列表不包含 'item' 的定义,也没有接受第一个参数的 'item' 的定义......

【问题讨论】:

  • C# 中的字段默认为私有。将您的声明更改为public List&lt;bar&gt; item;
  • 类和道具都是公开的。仍然出现错误,我的 linq 是否正确?

标签: c# linq


【解决方案1】:

鉴于 crepes 是 List&lt;Foo&gt;,您需要向 linq 查询添加一个额外的级别。

var item = crepes.Where(a => a.item.Any(x => x.doritos == "coolRanch")).FirstOrDefault();

【讨论】:

    【解决方案2】:

    你的itemaccess modifierprivate(这是class的C#默认值),它应该是public

    这也适用于您的doritos

    另外,由于您的 crepesList,因此添加额外的 LINQ 层(其他人也建议)以完全修复它,就像这样

    var item = crepes.Where(f => f.item.Any(b => b.doritos == "coolRanch")).FirstOrDefault(); //f is of foo type, b is of bar type
    

    【讨论】:

    • 类和道具都是公开的。仍然出现错误,我的 linq 是否正确?
    • @Chris 它现在会产生什么错误?我认为你也应该改变你的doritos
    【解决方案3】:

    如果你像这样修复你的课程

    class Foo
    {
        public List<Bar> Items { get; set; }
        public string Candy { get; set; }
        public string Beer { get; set; }
    }
    
    class Bar
    {
        public string Doritos { get; set; }
        public string Usb { get; set; }
    }
    

    您的查询将如下所示

    var crepes = new List<Foo>();
    var item = crepes.FirstOrDefault(f => f.Items.Any(b => b.Doritos == "coolRanch"));
    

    在这里,我们正在尝试获取第一个Foo,它在Items 中至少有一个Bar,其中Doritos == "coolRanch"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多