How to add Column header to a ListView in C#

2019-06-18 03:03发布

问题:

i'm having a ListView control with no columns.

an a list

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

i need to create columns for each list MyList item in the ListView along with one another column for Serial Number.

For example if MyList contains "A", "B" ,"C"

then the list view will be like

I know that we can do this using for or foreach loop like

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

but is there any way to do this using LINQ or LAMBDA Expression?

回答1:

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


回答2:

Here are 4 options
there are at least another 10 ways to do this,

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

Have you considered the KISS option?



回答3:

Just to make it a little clearer what Aliostad wrote and what the comments below this answer means:

So you currently have this code:

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

As you already mentioned you can write it also with a foreach. This would look like this:

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

In the second example it also iterates over the list. All it does it hides the local index variable i.

With this third example you're no going to hide also this iterating in a function that needs an action what to do with each item in the list:

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

Under the hood it still iterates over all the elements and performs some functionality on each element. You just don't write the loop by yourself, but that doesn't mean that it is in any way faster or better than your approach. It's just another (shorter) way to tell what you want to achieve.