开发者

How to get data from a ListView in Dictionary format in C# winforms

i've a ListView control like

How to get data from a ListView in Dictionary format in C# winforms

and a Dictionary

Dictionary<String,List<String>> MyDict

i need to fill the Dictionary with data in the ListView

So the Dictionary will be like

{ "S.No."  { "1","2","3" } }
{" A" {"A1", "", "" } }
{" B" {"B1", "B2", "" } }
{" C" {"C1", "C2", "C3" } }

using nested for loop we acn do thi开发者_运维问答s. But is there any way to do this using LINQ?


Use the ToDictionary method:

Dictionary<string, List<string>> dict =
    listView.Items
            .Cast<ListViewItem>()
            .ToDictionary(
                item => item.Text,
                item => item.SubItems
                            .Cast<ListViewItem.ListViewSubItem>()
                            .Select(subItem => subItem.Text)
                            .ToList());

EDIT

OK, I misread the question... This should work:

Dictionary<string, List<string>> dict =
    listView.Columns
            .Cast<ColumnHeader>()
            .ToDictionary(
                c => c.Text,
                c => listView.Items
                             .Cast<ListViewItem>()
                             .Select(i => i.SubItems[col.Index].Text)
                             .ToList());

(this works because the subitem at index 0 is actually the one that owns the other subitems)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜