views:

314

answers:

2

If you had a filled IQueryable variable.

How would you add a new empty entry in the end of that list?

Here is what I have to do:

  1. if there is 2 entry, add 3 empty entry
  2. if there is 0 entry, add 5 empty entry
  3. if there is 5 entry, add 5 empty entry

You can now see the pattern and it's for a repeater in asp.net.

Should I simply create a generic list(.toList()) and use the add functionality or is there any better way to do this?

+1  A: 

Well, if you're happy to convert it to IEnumerable<T> you can use

query.Concat(Enumerable.Repeat(new SomeRow(), 5)
     .Take(5);

Note that that will add the same extra row 5 times (and then cut the total down to 5). That won't work if you need to then be able to edit the rows; to do that, you'd want something like:

query.AsEnumerable()
     .Concat(Enumerable.Range(1, 5).
                       .Select(ignored => new SomeRow())
     .Take(5);

(I don't think there's a simpler way of calling the same function n times, but I could be wrong.)

EDIT: I've added the call to AsEnumerable() on the basis of comments. Basically calling AsEnumerable means "I've finished the SQL bit; do the rest in-process."

Jon Skeet
DAMNIT SKEET! Faster and with code! I was gonna pop open LINQpad and edit my answer, but forget it now!
Will
in the end, I used toList because the concat solution gave me this error: "Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator." right after I do anything with the IEnumerable variable
Fredou
I should have specified linq-to-sql, not linq in the tag, sorry
Fredou
@Fredou: Editing...
Jon Skeet
@Jon, thanks, I didn't know that and it's working
Fredou
+1  A: 

Well, I'd ToList it and use the Length property to determine what to do next.

But, if you're wanting not to do that, you could do a Union on an IEnumerable with five empty entries and then do a Take(5) on the result. Seems kind of redundant and not any shorter, tho.

Will