DerpyUnKnown DerpyUnKnown - 1 year ago 195
C# Question

Linq - selection item from ListView

How could I select all information about selected item, not only first column but all ?

For the first column I just need :

.Where(i => string.IsNullOrEmpty(searchBox.Text) || i.ID.StartsWith(searchBox.Text))
.Select(c => new ListViewItem(c.ID))

Lets say that next columns are :

I know that I have to use Linq segment which looks like :

(...).Select(c => { })

Thanks in advance!

Answer Source

You can use the ListViewItem ctor that accept an array of string (where elements after the first are the subitems)

Assuming your class has the properties LastName and Name

ListView.Items.AddRange(ListData.Where(i =>    
            || i.ID.StartsWith(searchBox.Text))
            .Select(c => new ListViewItem // this part
                 new string[]{c.ID, c.Name, c.LastName}

If the creation of a single ListViewItem get more complicated, consider using a funcion:

ListView.Items.AddRange(ListData.Where(i =>    
            || i.ID.StartsWith(searchBox.Text))
            .Select(c => CreateListViewItemFromElement(c)).ToArray());

private ListViewItem CreateListViewItemFromElement(MyClass element)
// handle the element to create a "complete" ListViewItem with subitems
    ListViewItem item = new ListViewItem(c.ID);
    return item;

(actually, I would use the latter in every case, it's much more readable to me)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download