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?
MyList.ForEach(name => listView1.Columns.Add(name));
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With