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

C# 在LINQ中查询/搜索列表(在某些情况下),c#,linq,C#,Linq,如何获取每个列表项的内容,以根据textQuery.Text进行测试,如果是命中,则写入名为listResx的ListView中的四列 List<TransResource> MasterList = new List<TransResource>(); foreach (TransResource x in resources.Values) { MasterList.Add(x); } ... public class TransResource {

如何获取每个列表项的内容,以根据
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;}
}
List MasterList=newlist();
foreach(resources.Values中的TransResource x)
{
主列表。添加(x);
}
...
公共类资源
{
公共字符串id{get;set;}
公共字符串en{get;set;}
公共字符串fr{get;set;}
公共字符串es{get;set;}
}
这将为您提供更小的匹配结果列表。你能从那里拿走吗

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
。您可以使用它来填充
列表视图
,例如使用
数据源
属性:

listResx.DataSource = hits;
listResx.DataBind();
试试这个:

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));
}

我不明白你在问什么。textQuery.Text在哪里?您希望使用哪种查询运算符(例如,我们搜索的是什么,什么定义了“命中”)?我们的源数据在哪里?也许这在将来会有所帮助:-)不幸的是,WinForms的ListView没有数据源和DataBind-ala WebForms。另外,
MasterList
不是数据源,而是
资源。值
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));
}