如何向LINQ查询添加额外行
本文关键字:添加 查询 LINQ | 更新日期: 2023-09-27 18:04:02
我有一个LINQ查询,从数据集检索行,并将其绑定到Winforms组合框:
namespace KimHongAutoAccessory.Forms
{
public partial class EngineFilter : Form
{
public EngineFilter()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void EngineFilter_Load(object sender, EventArgs e)
{
this.engineFilterTableAdapter.Fill(this.manufacturerEngine.EngineFilter);
var manufacturers = (from m in manufacturerEngine.EngineFilter
select new { m.ManufacturerID, m.Manufacturer })
.Distinct().ToList();
cboManufacturerFilter.DataSource = manufacturers.ToArray();
cboManufacturerFilter.DisplayMember = "Manufacturer";
cboManufacturerFilter.ValueMember = "ManufacturerID";
}
}
}
但是我想在组合框中添加一个联合项,比如单词"[All]":
|-------|
|TOYOTA |
|-------|
|KUBOTA |
|-------|
|FORD |
|-------|
|[All] |
|-------|
谁能给我一个小窍门?
假设您的"(All)"项目的ID有一个特殊值,以便您知道它何时被选中。我们假设它的ID是-1。
var manufacturers = (from m in manufacturerEngine.EngineFilter
select new { m.ManufacturerID, m.Manufacturer }
).Distinct().ToList();
manufactorers.Add(new { ManufacturerID = -1, Manufacturer = "(All)" });
cboManufacturerFilter.DataSource = manufacturers.ToArray();
// ... etc ...
下面是一个在LINQ中使用Union的快速示例,为了清晰起见,使用number。
var A = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var L = (from a in A where a > 5 select a)
.Distinct()
.Union(new int[]{-1})
.ToList();
OR在您的域:
var manufacturers = new []{ManufacturerID=-1, Manufacturer="(ALL)"}).AsEnumerable()
.Union(from m in manufacturerEngine.EngineFilter
select new { m.ManufacturerID, m.Manufacturer })
.Distinct()
.ToList();
工作示例(更接近问题域)
public class Manufacturer
{
public Manufacturer(int id, string name)
{
this.id = id;
this.name = name;
}
public int id { get; set; }
public string name { get; set; }
}
[Test]
public void test222()
{
var L = new List<Manufacturer>() { new Manufacturer(1, "Abc"), new Manufacturer(2, "def"), new Manufacturer(3, "hij"), new Manufacturer(4, "klm"), new Manufacturer(5, "nop"), new Manufacturer(6, "qrs"), new Manufacturer(7, "tuv"), new Manufacturer(8, "wxyz") };
var manufacturers =
new Manufacturer[] { new Manufacturer(-1, "[ALL]") }.AsEnumerable()
.Union(from m in L select new Manufacturer(m.id, m.name)).Distinct().ToList();
}
注意:如果你想在没有构造函数的情况下进行初始化,可以这样做:
new Manufacturer() {id=-1,name="[All]"}
意思是一样的
我知道这是旧的,但我想我会把它留给下一个家伙=)我可以在下面的匿名列表中添加一个匿名对象
var manufacturers = (from m in manufacturerEngine.EngineFilter
select new
{
ManufacturerID = (int)m.ManufacturerID,
Manufacturer = m.Manufacturer
}).ToList();
var allItem = new {
ManufacturerID = (int)-1,
Manufacturer = "ALL"
};
manufacturers.add(allItem);