2015-12-30 138 views
5

我有一个叫做cre的foo列表。我想回到foo其中bar.doritos == "coolRanch"Linq查询包含对象列表的对象列表

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抛出一个错误。 “列表中不包含的‘项目’和‘项目’接受的第一个参数没有定义的定义...

+1

'C#'中的字段默认为* private *。将您的声明更改为'公开列表项;' – Rob

+0

这两个类和道具都是公开的。仍然收到错误,是我的linq是正确的? – Chris

回答

11

鉴于crepes是List<Foo>,您需要为linq查询添加额外的级别。

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

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 
+0

类和道具都是公开的。仍然收到错误,是我的linq是正确的? – Chris

+0

@Chris现在产生了什么错误?我想你也应该改变你的'doritos' – Ian

2

如果修复此类

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

在这里,我们试图让具有至少一个Bar第一FooItems其中Doritos == "coolRanch"

相关问题