Reputation: 5281
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
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:
ToArray();
stays:
....ToArray();
select
:
....Select(p => p.Index.ToString()).ToArray();
where
:
....Where(p => p.IsSelected).Select(p => p.Index.ToString()).ToArray();
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
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