我想使用LINQ将自动完成功能设置为文本框。我已经用sqlCommands以一种方式做了。代码是
OleDbCommand cmdinst = new OleDbCommand("select distinct cst_City from cstTable", con);
OleDbDataReader drinst = cmdinst.ExecuteReader();
AutoCompleteStringCollection instcol = new AutoCompleteStringCollection();
while (drinst.Read())
{
instcol.Add(drinst.GetString(0));
}
txtCity.AutoCompleteCustomSource = instcol;
有了这个,我可以将autocomplecustom源添加到文本框中。现在我想用LINQ 添加相同的功能。请任何人帮助我..
答案 0 :(得分:3)
逐个向AutoCompleteStringCollection
添加字符串效率不高。因为当添加每个字符串时,如果没有足够的空间用于新字符串,则内部数组列表可确保其容量并调整存储大小(使其大两倍)。此外,每个添加的字符串CollectionChangedEvent
将尝试触发。当您通过AddRange
添加值时,存储空间只会调整一次,而CollectionChangedEvent
只会被触发一次。
此外,您只需应用Distinct
运算符,而不是分组并选择第一组。
var db = FooDataContext();
var cities = db.cstTable.Select(c => c.cst_City).Distinct().ToArray();
AutoCompleteStringCollection instcol = new AutoCompleteStringCollection();
instcol.AddRange(cities);
txtCity.AutoCompleteCustomSource = instcol;
答案 1 :(得分:1)
您查询缩小为
AutoCompleteStringCollection instcol = new AutoCompleteStringCollection();
dbContext.CstTable.Select (x => x.cst_City)
.GroupBy (x=>x).Select (grouping => grouping.First())
.ToList().ForEach (x=> instcol.Add(x))
txtCity.AutoCompleteCustomSource = instcol;
dbContext
是DataContext
派生对象。阅读this以了解如何创建此对象。
// custom datacontext class
public class CustomDataContext : DataContext
{
private static readonly string connectionString =
@"Data Source=.\SQLExpress;Initial Catalog=<db name>;" +
"Integrated Security=True"; // From the app.config
public CustomDataContext() : base(connectionString) { }
public Table<Cst_City> Cst_City
{
get { return this.GetTable<Cst_City>(); }
}
}
答案 2 :(得分:1)
根据我的理解,您希望将上述代码转换为LINQ等效代码。以下是步骤
1-创建数据库上下文对象
2-写查询
3-获取数据并显示
YourDBNameDataContext context = new YourDBNameDataContext();
var drinst = context.cstTable.Select(item => item.cst_City).Distinct();
foreach (string city in drinst )
{
instcol.Add(city);
}
txtCity.AutoCompleteCustomSource = instcol;