代码之家  ›  专栏  ›  技术社区  ›  Thorin Oakenshield

如何在C中向ListView添加列标题#

  •  7
  • Thorin Oakenshield  · 技术社区  · 14 年前

    我有一个没有列的ListView控件。

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

    我需要为每个列表创建列 MyList ListView 以及序列号的另一列。

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

    然后列表视图将如下所示

    alt text

    我知道我们可以用 for foreach 环状的

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

    但是有没有办法用 LINQ LAMBDA Expression

    3 回复  |  直到 14 年前
        1
  •  5
  •   Aliostad    14 年前
    MyList.ForEach(name => listView1.Columns.Add(name));
    
        2
  •  4
  •   Yona    14 年前

    这里有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 选择?

        3
  •  0
  •   Oliver    14 年前

    所以你现在有这个代码:

    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));