如何选择使用LINQ集合中的集合? [英] How do I select a collection within a collection using LINQ?
问题描述
我有以下的结构。
公共类ToolSettings
{
公共字符串扩展{搞定;组; }
公众的ObservableCollection<工具和GT;工具{搞定;组; }
}公共类工具
{
公共字符串名称{;组; }
公共字符串命令{获取设置; }
}//在应用code
公众的ObservableCollection< ToolSettings>设置{搞定;组; }
我想从设置集合,其中扩展等于某个字符串抢工具集合。
下面是我的LINQ code,但我只得到一个项目在我的收藏时,我知道还有更多。它看起来像它产生一个集合的集合,这就是为什么这里只有一个项目。
myListBox.ItemsSource =从我的设置
其中,i.Extension == myExtension
选择i.Tools;
编辑:
感谢所有的好(快速)的答案。原来我只需要第一个项目,但我知道方法的SelectMany会派上用场的未来。所以,感谢所有的抬起头。下面是我使用的完整的解决方案。
myListBox.ItemsSource =(从我的设置
其中,i.Extension == myExtension
选择i.Tools)。首先();
这会给你一个的IEnumerable<的ObservableCollection<工具>>
。它willprobably只有一个项目在里面,但该项目将是一个的ObservableCollection。如果您希望集合本身,粘性。首先()
(或 .FirstOrDefault()
)的结尾。
如果 i.Extension == myExtension
可以在集合中找到几个ToolsSettings(我猜没有),那么你就需要使用 .SelectMany()
I have the following structure.
public class ToolSettings
{
public string Extension { get; set; }
public ObservableCollection<Tool> Tools { get; set; }
}
public class Tool
{
public string Name { get; set; }
public string Command { get set; }
}
// Within app code
public ObservableCollection<ToolSettings> settings { get; set; }
I'd like to grab the Tools collection from the settings collection where the Extension equals a certain string.
Below is my LINQ code, but I'm only getting one item in my collection when I know there's more. It looks like it produces a collection of a collection, which is why there's only one item.
myListBox.ItemsSource = from i in settings
where i.Extension == myExtension
select i.Tools;
EDIT:
Thanks for all the good (and quick) answers. It turns out I only need the first item, but I know that the SelectMany method will come in handy in the future. So, thanks for all the heads up. Here is the full solution I used.
myListBox.ItemsSource = (from i in settings
where i.Extension == myExtension
select i.Tools).First();
That will give you an IEnumerable<ObservableCollection<Tool>>
. It willprobably only have one item in it, but that item will be a ObservableCollection. If you want that collection itself, tack .First()
(or .FirstOrDefault()
) at the end.
If i.Extension == myExtension
could find several ToolsSettings in the collection (I'm guessing not), then you will need to use .SelectMany()
这篇关于如何选择使用LINQ集合中的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!