How do I add a new record to an IQueryable variable?

silent200 picture silent200 · Jan 12, 2009 · Viewed 65.2k times · Source

The IQueryable results is queried from my db using LINQ, How do I add a new record to the IQueryable result.

Answer

Jon Skeet picture Jon Skeet · Jan 12, 2009

Do you want to add it to the database, or just to the list of results that other things like databinding will use?

If it's the former, you'll need to use the normal add operation for whatever kind of LINQ you're using, but to the table representation rather than the IQueryable. Queries only read data.

If it's the latter, use Enumerable.Concat to concatenate your existing sequence (the IQueryable) with a new one containing your extra entries (an array would do fine here, or a list), and use the result for binding etc. It's probably worth using AsEnumerable() first to make sure that Enumerable is used instead of Queryable. For example:

IQueryable<string> names = [...];
names = names.AsEnumerable().Concat(new[] { "(None)", "(Add new)" });