How to select a collection in a collection using LINQ?

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 want to grab the Tools collection from the settings collection, where Extension is equal to a specific line.

Below is my LINQ code, but I only get one item in my collection when I know it more. It looks like it is creating a collection of the collection, so there is only one element.

myListBox.ItemsSource = from i in settings 
                        where i.Extension == myExtension 
                        select i.Tools;

EDIT:

Thanks for all the good (and quick) answers. Turns out I only need the first element, but I know that the SelectMany method will come in handy in the future. So thanks for all the heads. Here is the complete solution I used.

myListBox.ItemsSource = (from i in settings 
                         where i.Extension == myExtension 
                         select i.Tools).First();
+2
source share
5 answers

IEnumerable<ObservableCollection<Tool>>. , , , ObservableCollection. , .First() ( .FirstOrDefault()).

i.Extension == myExtension ToolsSettings ( , ), .SelectMany()

+1
myListBox.ItemsSource = settings.Where(s => s.Extension == myExtension)
                                .SelectMany(s => s.Tools);

, :

myListBox.ItemsSource = from s in settings
                        where (s.Extension == myExtension)
                        from t in s.Tools
                        select t;
+8

:

myListBox.ItemsSource = (from i in settings 
                         where i.Extension == myExtension
                         from t in i.Tools
                         select t);
+1

.SelectMany(), , . Extension , .Single(), .

0

. , , ToolSettings, Extension , - , Tools, ObservableCollection<Tool>.

, Tool, . SelectMany Enumerable:

myListBox.ItemsSource = settings.Where(i => i.Extension == myExtension).
    SelectMany(i => i.Tools);

, , :

myListBox.ItemsSource = 
    from i in settings
    where i.Extension == myExtension
    from t in i.Tools
    select t;

SelectMany, .

0

All Articles