Ng Zen
Ng Zen

Reputation: 319

C# Check if data exists in List View Windows Form

What I want to do is actually getting a set of data then group it by the identifier, something like this:

123456 123456 456789 456789 456789 135790

to

Name       Quantity
123456        2
456789        3 
135790        1

What I've done so far:

Foreach(string name in itemlist) //itemlist = 123456,123456... as mentioned above
{
  var listitems= lvTest.Items.Cast<ListViewItem>;
  bool exists = listitems.Where(item => item.Text == name).Any(); // to check if item name is already exists in list view
  if (!exists)
  {
        ListViewItem lvItem = new ListViewItem(new string[] { name, "1" });
        lvTest.Items.Add(lvItem);
   }
        else
   {
        ListViewItem lvItem = lvTest.Items.Cast<ListViewItem>.Where(item => item.Text == name).FirstOrDefault();
        int count = (int)lvItem.SubItems[1].Text;
        count = count + 1;
        lvItem.SubItems[1].Text = count.ToString();
   }
}

But this won't work due to the issue "Cannot assign method group to an implicitly-typed local variable" in the line of

var listitems= lvTest.Items.Cast<ListViewItem>

Please help and thanks in advance.

Upvotes: 0

Views: 531

Answers (2)

Ng Zen
Ng Zen

Reputation: 319

Gosh, end up the issue is because I did not put bracket after Cast function. It should be

var listitems= lvTest.Items.Cast<ListViewItem>();

Upvotes: 1

dinesh subasingha
dinesh subasingha

Reputation: 11

Why don't use something like this,

List<string> lstString = new List<string> { "123456", "123456", "456789", "456789", "456789", "135790" };

var lstGroupList = lstString .GroupBy(item => item,
              (key, group) => new { key, Items = group.ToList()}).ToList();

Upvotes: 1

Related Questions