DerpyUnKnown DerpyUnKnown - 2 days ago 5
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 :

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


Lets say that next columns are :
Name
,
LastName


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

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


Thanks in advance!

Answer

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 =>    
            string.IsNullOrEmpty(searchBox.Text) 
            || i.ID.StartsWith(searchBox.Text))
            .Select(c => new ListViewItem // this part
               (
                 new string[]{c.ID, c.Name, c.LastName}
               )).ToArray());

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

ListView.Items.AddRange(ListData.Where(i =>    
            string.IsNullOrEmpty(searchBox.Text) 
            || 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)

Comments