Vincent Dagpin
Vincent Dagpin

Reputation: 3611

Linq in selecting item from ListViewItemCollections in c#

how to select a ListViewItem from ListViewItemCollections using Linq in C#?

i tried on using this but it didn't work..

ListViewItemCollections lv = listview1.items;

var test = from xxx in lv where xxx.text = "data 1" select xxx;


test   <--- now has the listviewitem with "data 1" as string value..

Upvotes: 17

Views: 18871

Answers (4)

m.qayyum
m.qayyum

Reputation: 411

If you want to limit your search to just one column you can do so with

IEnumerable<ListViewItem> lv = listView.Items.Cast<ListViewItem>();

var rows =  from x in lv
            where x.SubItems[columnIndex].Text == searchTerm
            select x;

if (rows.Count() > 0)
{
    ListViewItem row = rows.FirstOrDefault();

    //TODO with your row
}

Upvotes: 2

Homam
Homam

Reputation: 23871

To get an enumerator of ListViewItem, you have to cast the Items collection of ListView:

IEnumerable<ListViewItem> lv = listview1.items.Cast<ListViewItem>();

Then, you can use LINQ with it:

 var test = from xxx in lv 
            where xxx.text = "data 1" 
            select xxx;

Upvotes: 35

Ahmed Magdy
Ahmed Magdy

Reputation: 6040

ListViewItemCollections lv = listview1.items;

var test = from ListViewItem xxx in lv where xxx.text == "data 1" select xxx;

or

listview1.items.Cast<ListViewItem>().Where(i => i.text == "date 1");

Upvotes: 7

MartinStettner
MartinStettner

Reputation: 29174

ListViewItemCollection does only implement IEnumerable (instead of IEnumerable<ListViewItem>), therefore the compiler cannot infer the type of xxx and the LINQ query doesn't work.

You need to cast the collection in order to work with it like

var test = from xxx in lv.Cast<ListViewItem>() where xxx.text="data 1" select xxx;

Upvotes: 1

Related Questions