shapper wrote:
I have the following LINQ:
List<Tagtags = (from t in
database.Tags
select t).ToList();
I need to restrict my results and for that I have two parameters:
StartWidth and N
I would like to change my Linq query to do as follows:
1. Select all tags which tag.Name starts with the value contained in
StartWidth parameter.
StartWidth or StartsWith? The latter would make more sense.
NOTE: Both tag.Name and StartWidth are strings.
AND
2. Get the first N tags from that list ordered alphabetically.
Alphabetically by what? I assume "Name".
NOTE: If N = 0 then get all tags
How can I do this?
Well, just write it down in steps. This is all tags:
from t in database.Tags
select t
Now we want all tags where tag.name starts with "StartsWith " (I assume). So:
from tag in database.Tags
where tag.Name.Starts With(StartsWith )
select tag
We want them ordered by Name:
from tag in database.Tags
where tag.Name.Starts With(StartsWith )
orderby tag.Name
select tag
This is the sequence we want. Now we want to limit the number of elements,
for which LINQ offers the extension method "Take":
var q =
from tag in database.Tags
where tag.Name.Starts With(StartsWith )
orderby tag.Name
select tag;
List<Tagtags = (N 0 ? q.Take(N) : q).ToList();
And that's all there is to it. See also
http://msdn.microsoft.com/vcsharp/aa336746 for examples of LINQ in action.
--
J.