Search code examples
c#linqasp.net-mvc-viewmodel

iterate an object and create a new object with group by C# mvc


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


Solution

  • 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)})