我有一个List<List<String>>
MyList,其中包含
{ "A1","B1","C1" }
{ "A2","B2","C2" }
{ "A3","B3","C3" }
我需要将它添加到具有三列的ListView控件
所以列表视图就像
__Clm1________________Clm2________________Clm3_______________
A1 A2 A2
B1 B2 B3
C1 C2 C3
有没有办法使用LINQ
来做到这一点编辑以下是我的解决方案:
ListViewItem[] lItem = MyList.Select(
X => new ListViewItem(X.ToArray())
).ToArray();
listView1.Items.AddRange(lItem);
但在这里我需要添加一个Index .... List视图就像
___S.No __Clm1________________Clm2________________Clm3_______________
1 A1 A2 A2
2 B1 B2 B3
3 C1 C2 C3
如何将索引添加到列表视图?
答案 0 :(得分:4)
就个人而言,我觉得这个更清洁了:
var myList = new List<List<string>>()
{
new List<string>(){ "A1","B1","C1" },
new List<string>(){ "A2","B2","C2" },
new List<string>(){ "A3","B3","C3" },
};
listView.BeginUpdate();
foreach (var row in myList)
{
var item = new ListViewItem(listView.Items.Count.ToString());
item.SubItems.AddRange(row);
listView.Items.Add(item);
}
listView.EndUpdate();
答案 1 :(得分:3)
是的..我有一个解决方案......这是
int i=1;
ListViewItem[] lItem =MyList.Select(X=> new ListViewItem(new String[]{i++.ToString()}.Concat(X).ToArray())).ToArray();
listView1.Items.AddRange(lItem);
答案 2 :(得分:3)
如果您发现这样的ListView
控件很多,那么添加一些简单的扩展方法可能是值得的:
public static class ListViewExtensions
{
public static ListView AddItems(this ListView listView,
IEnumerable<ListViewItem> items)
{
listView.Items.AddRange(items.ToArray());
return listView;
}
public static ListViewItem WithSubItems(this ListViewItem item,
IEnumerable<string> subItems)
{
item.SubItems.AddRange(subItems.ToArray());
return item;
}
}
结果代码变得非常简洁明了:
var rows = new List<List<string>>()
{
new List<string>(){ "A1","B1","C1" },
new List<string>(){ "A2","B2","C2" },
new List<string>(){ "A3","B3","C3" },
};
listView1.AddItems(
rows.Select(
(row, index) => new ListViewItem(index.ToString())
.WithSubItems(row)
)
);
答案 3 :(得分:1)
使用带有索引的Select
重载:
var rows = new List<List<string>>()
{
new List<string>(){ "A1","B1","C1" },
new List<string>(){ "A2","B2","C2" },
new List<string>(){ "A3","B3","C3" },
};
listView1.Items.AddRange(
rows.Select(
(row, index) => new ListViewItem(
new[] { index.ToString() }
.Concat(row)
.ToArray()
)
)
.ToArray()
);
我个人会使用不同的样式来执行此操作(本地委托,或扩展方法+流利的语法),因为我不喜欢内联调用ToArray,但这与内置的内容非常接近得到:)。
如果您对扩展方法+流利语法选项感兴趣,请参阅我的其他答案。