0

我想设置一个按钮,当我按下它时,它将获取文本框中的字符串,并在以该字符串或字符开头的数据表上的某个字段上查找所有记录。然后在 Listbox 或 DataGridViewer 中显示结果

这是我已经实现的一小段代码,但我无法继续

   private void button3_Click(object sender, EventArgs e)
    {
        MyLinqDataContext MyData = new MyLinqDataContext();
        MyList myLambda =  MyData.MyLists.First(lambda => lambda.First_Name.StartsWith(TxtFirstName.Text));

    }

提前致谢 :)

4

2 回答 2

2

1) First in linq, returns a single record. you will want to use Where to return a list.

2) Where in linq will return a collection of type IEnumerable<T>. You will either need to call .ToList() on it afterwards, or use var as the type.

3) You shouldn't need to create a new data context to run this against, as long as you have the original table in a queryable format.

final code, by example

private void button3_Click(object sender, EventArgs e)
{
    var myLambda =  MyDataTable.AsEnumerable().Where(lambda => lambda.Field<string>("First_Name").StartsWith(TxtFirstName.Text));
    //var should be of the type IEnumerable<DataRow>

    //from here, we can use this var as the DataSource for another display
    resultsBox.DataSource = myLambda;
    //assuming resultsBox can interpret a datarow correctly.  
    //You may need to select First_Name only, or some other data, out of the returned values.
}

Alternatively, using the data context

private void button3_Click(object sender, EventArgs e)
{
    MyLinqDataContext MyData = new MyLinqDataContext();
    var myLambda =  MyData.MyLists.Where(lambda => lambda.First_Name.StartsWith(TxtFirstName.Text));

    resultsBox.DataSource = myLambda;
}
于 2013-04-17T16:28:16.397 回答
1

如果你想找到你不想使用的所有记录你.First()想使用.Where()所以

private void button3_Click(object sender, EventArgs e)
{
    MyLinqDataContext MyData = new MyLinqDataContext();
    MyList myLambda =  MyData.MyLists.Where(lambda => lambda.First_Name.StartsWith(TxtFirstName.Text[0].ToString()));
}

上面使用字符串 [0] 的第一个索引来检索第一个字符。

于 2013-04-17T16:22:38.310 回答