Aaron Thomas
Aaron Thomas

Reputation: 5281

How to write a query in method syntax

If there is an ObservableCollection of class Printer called Printers...
and each Printer contains properties IsSelected (bool) and Index (int)...
how can I transform the following LINQ query from query syntax to method syntax?

string[] printerListing = 
    (from p in Printers
    where p.IsSelected
    select p.Index.ToString()).ToArray();

I came up with the following, but it only returns the first Printer from the query (split across multiple lines for readability):

var printers2 =
    Printers.Where(p => p.IsSelected)
    .FirstOrDefault()
    .Index.ToString().ToArray();

Upvotes: 1

Views: 62

Answers (3)

René Vogt
René Vogt

Reputation: 43876

string[] printerListing = 
    (from p in Printers
     where p.IsSelected
     select p.Index.ToString()).ToArray();

You can do this simply step by step from the end of your query to the beginning:

  1. ToArray(); stays:

    ....ToArray();
    
  2. select:

    ....Select(p => p.Index.ToString()).ToArray();
    
  3. where:

    ....Where(p => p.IsSelected).Select(p => p.Index.ToString()).ToArray();        
    
  4. from (the source):

    Printers.Where(p => p.IsSelected).Select(p => p.Index.ToString()).ToArray();   
    

So finally:

string[] printerListing = 
               Printers
                   .Where(p => p.IsSelected)
                   .Select(p => p.Index.ToString())
                   .ToArray();   

Actually, it's also working the other way round, but sometimes the reverse order is easier to follow.

Upvotes: 2

Dmitriy Kovalenko
Dmitriy Kovalenko

Reputation: 3616

You used FirstOrDefault() so it will return one first element where isSelected = true. Use

var printers2 = Printers.Where(p => p.IsSelected)
                        .Select(x => x.Index.ToString).ToArray();

Upvotes: 0

David L
David L

Reputation: 33815

Use .Select(), which functions like the select keyword in query syntax.

var printers2 = Printers
                    .Where(p => p.IsSelected)
                    .Select(x => x.Index.ToString())
                    .ToArray();

Upvotes: 3

Related Questions