Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an empty row in a combobox filled by linq?

Tags:

linq

I have a list of Items, given by Linq from the DB. Now I filled a ComboBox with this list.

How I can get an empty row in it?

My problem is that in the list the values aren't allowed to be null, so I can't easily add a new empty item.

like image 665
PassionateDeveloper Avatar asked Dec 18 '25 00:12

PassionateDeveloper


1 Answers

You can use Concat() to append your real data after the static item. You'll need to make a sequence of the empty item, which you can do with Enumerable.Repeat():

list.DataSource = Enumerable.Repeat(new Entity(), 1)
                 .Concat(GetEntitiesFromDB());

Or by defining a simple extension method (in set theory a singleton is a set with cardinality 1):

public IEnumerable<T> AsSingleton<T>(this T @this)
{
    yield return @this;
}

// ...
list.DataSource = new Entity().AsSingleton().Concat(GetEntitiesFromDB());

Or even better, write a Prepend method:

public IEnumerable<T> Prepend<T>(this IEnumerable<T> source, params T[] args)
{
    return args.Concat(source);
}


// ...
list.DataSource = GetEntitiesFromDB().Prepend(new Entity());
like image 197
dahlbyk Avatar answered Dec 19 '25 18:12

dahlbyk