-3

how do i loop through an object and create a new object in C# i have a view model eg:

pViewModel  {
public itemFullName {get;set;}
public Item Item{get;set;}
}
public Item{
public int itemId{get;set;}
}

I want to create a new object after finding matching fullname but different id so my new object will have a list of itemFullName, item.itemid(pipedelimited values for all the items in the previous list) in it.

Any help will be awesome. thank you

  • I'm having difficulty understanding what you're asking for. Can you provide some sample input and expected output? Maybe use JSON notation or something? – StriplingWarrior Jul 17 '19 at 21:53
  • I have list which has 237 items with duplicate itemfullname but with different set of item.itemid. I want to get a new list with duplicate itemfullname and item.itemid ( which is repeating) – user1098924 Jul 17 '19 at 22:01

1 Answers1

1

It sounds like you want to group a list of your models by itemFullName. Here's how you might do that to create objects of an anonymous type.

var itemsAndIds = list
    .GroupBy(m => m.itemFullName, m => m.Item.itemId)
    .Select(g => new {ItemFullName = g.Key, ItemIds = string.Join("|", g)})
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • this is great. but if there are additional properties in the viewmodel say like "itemAddress" , itemCountry. is there a way to append those to the existing itemsandids object? – user1098924 Jul 18 '19 at 03:29
  • Yes, there are ways. For example, you could add new properties to the anonymous object for those. You'd probably want to change the second argument to GroupBy to `m => m.Item` and then select those difference parts as part of your Select (e.g. `g.Select(i => i.itemAddress)`) – StriplingWarrior Jul 18 '19 at 15:16