我有一个项目列表,由Linq从DB中给出.现在我用这个列表填充了一个ComboBox.
我怎么能得到一个空行?
我的问题是,在列表中,值不允许为null,因此我无法轻松添加新的空项.
您可以使用Concat()在静态项后附加实际数据.你需要创建一个空项的序列,你可以使用Enumerable.Repeat():
list.DataSource = Enumerable.Repeat(new Entity(), 1)
.Concat(GetEntitiesFromDB());
Run Code Online (Sandbox Code Playgroud)
或者通过定义一个简单的扩展方法(在集合论中,单例是一个基数为1的集合):
public IEnumerable<T> AsSingleton<T>(this T @this)
{
yield return @this;
}
// ...
list.DataSource = new Entity().AsSingleton().Concat(GetEntitiesFromDB());
Run Code Online (Sandbox Code Playgroud)
或者甚至更好,编写一个Prepend方法:
public IEnumerable<T> Prepend<T>(this IEnumerable<T> source, params T[] args)
{
return args.Concat(source);
}
// ...
list.DataSource = GetEntitiesFromDB().Prepend(new Entity());
Run Code Online (Sandbox Code Playgroud)