Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querying existing ListView items with LINQ

Tags:

c#

listview

linq

The ListView I have populates through these loops resulting in four columns being filled

// Create a ResXResourceReader
ResXResourceReader rdr0 = new ResXResourceReader(textPath1.Text + ".resx");
ResXResourceReader rdr1 = new ResXResourceReader(textPath1.Text + ".es.resx");
ResXResourceReader rdr2 = new ResXResourceReader(textPath1.Text + ".fr.resx");

foreach (DictionaryEntry d in rdr0)
{
    TransResource x = new TransResource();
    x.id = d.Key.ToString();
    x.en = d.Value.ToString();
    resources.Add(x.id, x);
}

foreach (DictionaryEntry d in rdr1)
{
    TransResource x = resources[d.Key.ToString()];
    x.fr = d.Value.ToString();
}

foreach (DictionaryEntry d in rdr2)
{
    TransResource x = resources[d.Key.ToString()];
    x.es = d.Value.ToString();
}

foreach (TransResource x in resources.Values)
{
    string[] row = { x.id, x.en, x.fr, x.es };
    var listViewItem = new ListViewItem(row);
    listResx.Items.Add(listViewItem);
}

What I want to do is query all of the results in this ListView against what is entered in textboxQuery. If any field in the entire listview contains the string from textboxQuery I want it to be displayed in a new listview (lets say listviewQueryresult). I've had many failed attempts at this but I know it is possible through LINQ.

like image 762
rbelliv Avatar asked Mar 15 '13 13:03

rbelliv


1 Answers

Because ListView.Items implements IEnumerable, but does not implement IEnumerable<T> you have to cast it to IEnumerable<ListViewItem> first, to query it using LINQ to Objects:

var results = listResx.Items.Cast<ListViewItem>()
                            .Where(x => YourPredicate(x));

If any field in the entire listview contains the string from textboxQuery I want it to then be displayed in a new listview (lets say listviewQueryresult)

For that, the predicate would be just:

var results = listResx.Items.Cast<ListViewItem>()
                            .Where(x => x.Text.Contains(textboxQuery));
like image 148
MarcinJuraszek Avatar answered Oct 22 '22 04:10

MarcinJuraszek