如何在Lambda表达式中使用where

时间:2014-08-06 18:00:24

标签: c# wpf entity-framework lambda

我有4个文本框[name = txtone,name = txttwo,name = txtthree,name = txtfour]。我也有一个搜索按钮。在按钮单击事件中,我想在表格中搜索搜索的输入是我上面给出的那些文本框。我正在使用Entity Framework和lambda表达式来加载数据网格。

我正在使用的代码..

     var result = Entities.pos.ToList()
           .OrderBy(x => x.ID)           
           .Skip(initialRow)           
            .Take(finalRow - initialRow) ;     
            this.datagrid1.ItemsSource = result;

我如何使用where条件?还有一件事,在搜索中没有字段是强制性的。数据库表字段是[ID,NAME,AGE,DOB]

感谢。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

var result = pO2GOEntities.po2go_gm_pos
           .Where(x=>x.SomeCoulumn ==txtone.Text || x.SomeCoulumn == txttwo.Text ---------)
           .OrderBy(x => x.ID)           
           .Skip(initialRow)           
           .Take(finalRow - initialRow)
           .ToList() ;     
            this.datagrid1.ItemsSource = result;

UPDATE:

你可以这样做:

 var result = pO2GOEntities.po2go_gm_pos.ToList();

    if(!string.IsNullOrEmpty(txtone.Text))
    {
        result = result.Where(x=>x.SomeCoulmn == txtone.Text);
    }
    if(!string.IsNullOrEmpty(txttow.Text))
    {
        result = result.Where(x=>x.SomeCoulmn == txttwo.Text);
    }
--------------
--------------
--------------

var finalResult = result.OrderBy(x => x.ID)           
                        .Skip(initialRow)           
                        .Take(finalRow - initialRow)
                        .ToList() ;

答案 1 :(得分:0)

您可以使用 .where 并指定条件。 请查看此101 Linq Samples

<强> EDIT1:

 var result = pO2GOEntities.po2go_gm_pos
       .Where(x=>x.clmOne==txtone.Text || x.clmTwo== txttwo.Text|| x.clmThree==txtThree.text || x.clmFour==txtFour.text)
       ..
       .ToList() ;     
 this.datagrid1.ItemsSource = result;

<强> EDIT2: 如果参数为空,则where子句将其排除。

 var result = pO2GOEntities.po2go_gm_pos
       .Where( (x=>x.clmOne==txtone.Text || string.IsNullOrEmpty(param1))&&  (x.clmTwo==txtTwo.text || string.IsNullOrEmpty(param1)) && ..)
       ..
       .ToList() ;