在LINQ中查询/搜索列表(在某些情况下)

时间:2013-03-15 21:39:17

标签: c# linq

如何才能获取要针对textQuery.Text进行测试的每个列表条目的内容,如果是命中,则要写入名为listResx的ListView中的四个列?

List<TransResource> MasterList = new List<TransResource>();

foreach (TransResource x in resources.Values)
{
     MasterList.Add(x);
}
...
public class TransResource
{
    public string id {get; set;}
    public string en {get; set;}
    public string fr {get; set;}
    public string es {get; set;}
}

3 个答案:

答案 0 :(得分:1)

var resultList = MasterList.Where(x => x.id == textQuery.Text || x.en == textQuery.Text || x.fr == textQuery.Text || x.es == textQuery.Text).ToList();

这应该会给你较小的匹配结果列表。你能从那里拿走吗?

答案 1 :(得分:0)

string keyword = textQuery.Text;

var hitsQuery = from i in MasterList
                where i.en == keyword ||
                      i.es == keyword ||
                      i.fr == keyword ||
                      i.id == keyword
                select i;

var hits = hitsQuery.ToList();

hist将是List<TransResource>。您可以使用它来填充ListView,例如使用DataSource属性:

listResx.DataSource = hits;
listResx.DataBind();

答案 2 :(得分:0)

试试这个:

var matches = resources.Values.Where(x=>x.id==txtQuery.Text ||
                                        x.en==txtQuery.Text ||
                                        x.fr==txtQuery.Text ||
                                        x.es==txtQuery.Text);

foreach(var item in matches)
{   
   string displayItem = item.id + " " + item.en;
   listResx.Items.Add(new ListViewItem(displayItem));
}

或者使用更少的代码行:

foreach(var item in resources.Values.Where(x=>x.id==txtQuery.Text ||
                                              x.en==txtQuery.Text ||
                                              x.fr==txtQuery.Text ||
                                              x.es==txtQuery.Text))
{   
   string displayItem = item.id + " " + item.en;
   listResx.Items.Add(new ListViewItem(displayItem));
}
相关问题