2010-11-02 38 views
6

我有一个没有列的ListView控件。如何将列标题添加到C#中的ListView中#

的列表

List<String> MyList=new List<string>(); 

我需要在序列号的ListView随着彼此列创建列每个列表MyList项目。

例如,如果MyList包含"A", "B" ,"C"

则列表视图会像

alt text

我知道,我们可以使用forforeach圈状

listView1.Columns.Add("S.No") 
for(int i=0;i<MyList.Count;i++) 
    { 
     listView1.Columns.Add(MyList[i]) 
    } 

做到这一点但有没有办法使用来做到这一点或LAMBDA Expression

回答

4
MyList.ForEach(name => listView1.Columns.Add(name)); 
+0

我需要添加“S.No”列。 – 2010-11-02 12:03:38

+3

您不必添加S.No与Linq。 Linq只是编写使代码可读的循环的捷径,仅此而已。如果必须,请使用列表的InsertAt将S.No作为列表中的第一项添加。 – Aliostad 2010-11-02 12:05:13

0

只是为了更清楚一点什么Aliostad写的,什么这个答案下面的评论中表示:

所以,你现在有这样的代码:

listView1.Columns.Add("S.No") 
for(int i=0;i<MyList.Count;i++) 
{ 
    listView1.Columns.Add(MyList[i]) 
} 

正如你已经提到的,你可以写它也与foreach。这看起来像这样:

listView1.Columns.Add("S.No") 
foreach(var item in MyList) 
{ 
    listView1.Columns.Add(item) 
} 

在第二个示例中它也遍历列表。它所做的就是隐藏本地索引变量i

由于你没有打算也隐藏这个迭代中,需要一个动作做什么用列表中的每个项目的功能这第三个例子:

listView1.Columns.Add("S.No") 
MyList.ForEach(name => listView1.Columns.Add(name)); 

引擎盖下它仍然遍历所有元素并在每个元素上执行一些功能。你只是不要自己编写循环,但这并不意味着它比你的方法更快或更好。这是另一种(较短)的方式来告诉你想要达到的目标。

4

这里有4个选项
至少有另外10种方法可以做到这一点,

var myList = new List<string>() { "A", "B", "C" }; 

// 1: Modify original list and use List<>.ForEach() 
myList.Insert(0, "S. No"); 
myList.ForEach(x => lisView.Columns.Add(x)); 

// 2: Add first column and use List<>.ForEach() 
listView.Columns.Add("S. No"); 
myList.ForEach(x => listView.Columns.Add(x)); 

// 3: Don't modify original list 
(new[] { "S. No" }).Concat(myList).ToList() 
    .ForEach(x => listView.Columns.Add(x)); 

// 4: Create ColumnHeader[] with Linq and use ListView.Columns.AddRange() 
var columns = (new[] { "S. No"}).Concat(myList) 
    .Select(x => new ColumnHeader { Text = x }).ToArray(); 
listView.Columns.AddRange(columns); 

你有没有考虑在KISS选项?

相关问题