如何使用linq resultset c#添加或预挂硬编码数据
本文关键字:编码 数据 添加 何使用 linq resultset | 更新日期: 2023-09-27 17:53:31
假设下面的查询返回城市ID和城市名称,但如果我想pre-pend
一些硬编码数据与linq
的结果,那么我怎么能做到呢
var cityList = network.Continents
.SelectMany(continent => continent.Countries)
.Where(ctry => ctry.Id == "country")
.SelectMany(ctry => ctry.Cities,
c => new City { Id = c.Id, Name = c.Name })
.ToList();
上面的查询将以这种方式返回数据
City ID City Name
-------- ------------
1 Bombay
2 Kolkata
3 Delhi
但是我想要这样的结果
City ID City Name
--------- -----------
0 --Select City--
1 Bombay
2 Kolkata
3 Delhi
所以我想将此数据0 as ID and --Select City-- as Name
添加到返回linq查询的列表中。帮助我与样例代码。由于
嗯…只是Insert()
?
var cityList = network.Continents
.SelectMany(continent => continent.Countries)
.Where(ctry => ctry.Id == "country")
.SelectMany(ctry => ctry.Cities,
c => new City { Id = c.Id, Name = c.Name })
.ToList();
// yup, this is what I would do...
cityList.Insert(0, new City{ Id = 0, Name = "--Select City--"});
与Enumerable.Concat
的解
City[] prepend = new City[] {new City { Id = 0, Name = "--Select City--"}};
IEnumerable<City> cities = network.Continents
.SelectMany(continent => continent.Countries)
.Where(ctry => ctry.Id == "country")
.SelectMany(ctry => ctry.Cities,
c => new City { Id = c.Id, Name = c.Name });
var citySequence = prepend.Concat(cities);
var cityList = citySequence.ToList();