C
C#2y ago
ogie1985

Filter and give back a new object with Linq

Simulating the current situation:
class MyDTO{
int Id {get;set;}
int IdOfSomethingElse{get;set;}
string Description {get;set;}
string Description2 {get;set;}
}
class MyDTO{
int Id {get;set;}
int IdOfSomethingElse{get;set;}
string Description {get;set;}
string Description2 {get;set;}
}
`
var myDTOList = new List<MyDTO>()
{
new MyDto{
Id = 1,
IdOfSomethingElse = 2,
Description = "blabla1",
Description2 = "blabla11"
},

new MyDto{
Id = 2,
IdOfSomethingElse = 2,
Description = "blabla2",
Description2 = "blabla22"
}


new MyDto{
Id = 2,
IdOfSomethingElse = 3,
Description = "blabla3",
Description2 = "blabla33"
},

new MyDto{
Id = 4,
IdOfSomethingElse = 3,
Description = "blabla4",
Description2 = "blabla44"
}
}

How can I transform myDTOList to a new object with linq to the following object:

class MyNewDTO{
int IdOfSomethingElse= 2
List<string> descriptionList = will contain description of idofsomethingelse
List<string> descriptionList2 = will contain description2 of idofsomething else

}
var myDTOList = new List<MyDTO>()
{
new MyDto{
Id = 1,
IdOfSomethingElse = 2,
Description = "blabla1",
Description2 = "blabla11"
},

new MyDto{
Id = 2,
IdOfSomethingElse = 2,
Description = "blabla2",
Description2 = "blabla22"
}


new MyDto{
Id = 2,
IdOfSomethingElse = 3,
Description = "blabla3",
Description2 = "blabla33"
},

new MyDto{
Id = 4,
IdOfSomethingElse = 3,
Description = "blabla4",
Description2 = "blabla44"
}
}

How can I transform myDTOList to a new object with linq to the following object:

class MyNewDTO{
int IdOfSomethingElse= 2
List<string> descriptionList = will contain description of idofsomethingelse
List<string> descriptionList2 = will contain description2 of idofsomething else

}
1 Reply
Angius
Angius2y ago
Perhaps with .Aggregate()?