[英]filling combo box using LINQ query (distinct)
I have a combocox the name is "cmbModel" I want to fill the database with two different values in a table. 我有一个combocox,名称是“ cmbModel”,我想用表中的两个不同值填充数据库。 This is what I have done:
这是我所做的:
private void Form1_Load(object sender, EventArgs e)
{
using (LINQSQLDataContext db = new LINQSQLDataContext())
{
cmbModel.DisplayMember = "szModel";
cmbModel.DataSource = db.VehEcus.ToList<VehEcu>();
}
}
this will fill my cmbModel with szModel column of my table but I want to avoid repeating , how can I use " distinct
" in query to achieve my goal? 这将用表的szModel列填充我的cmbModel,但是我想避免重复,如何在查询中使用“
distinct
”来实现我的目标? and also I want to show 2 items of my table like " modelID-szModel
" in my combobox 而且我还想在组合框中显示表格的2个项目,例如“
modelID-szModel
”
Thanks 谢谢
如果您只想显示单个列,则可以选择该列并使用Distinct
:
cmbModel.DataSource = db.InfoProg_VehEcus.Select(x => x.szModel).Distinct();
You can apply Distinct() at any point after your query. 您可以在查询后的任何时候应用Distinct()。 I recommend doing it before you enumerate.
我建议您先列举一下。
To create the custom modelID-szModel field, you can enumerate the query using AsEnumerable(), then create an anonymous type and use String.Format to concatenate your values into your new field. 要创建自定义的modelID-szModel字段,可以使用AsEnumerable()枚举查询,然后创建一个匿名类型并使用String.Format将值连接到新字段中。
using (LINQSQLDataContext c = new LINQSQLDataContext ())
{
var items = c.VehEcus.Select(t => new
{
a = t.szModel,
b = t.modelID
}).Distinct()
.AsEnumerable().Select(t => new
{
displayMember = String.Format("{0}-{1}", t.a, t.b)
});
cmbModel.DisplayMember = "displayMember";
cmbModel.DataSource = items.ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.