How to create a sublist from the list of records using linq?

  • Thread starter Thread starter Anantha Asamani
  • Start date Start date
A

Anantha Asamani

Guest
I might have failed to explain the question properly in the title, below explanation would suffice.


class Person
{
public string Name { get; set; }
public int ID { get; set; }
public string Pet {get;set;}
public int PetID {get;set;}
}
//Consider below object as record set coming from database.
List<Person> categories = new List<Person>()
{
new Person {Name="John Doe", ID=001, Pet="Dog", PetID=001},
new Person {Name="John Doe", ID=001, Pet="Cat", PetID=002},
new Person {Name="John Doe", ID=001, Pet="Parrot", PetID=003}
};


//currently I wrote the linq query as below


var obj = (from p in Person
select new Person
{
Name= p.Name,
ID= p.ID,
Pet= p.Pet
PetID=p.PetID
}).ToList();

// I want to change the linq query to return the data with a sublist in the object, as below.

I'm not sure if the below linq query would work properly.


public class NewPerson
{
public string Name{get;set;}
public int Id{get;set;}
public List<Pets> pet{get;set;}
}

public class Pets
{
public string PetName{get;set;}
public int PetID {get;set;}
}

var obj = (from p in Person
select new NewPerson
{
Name= p.Name,
ID= p.ID,
select new List<Pets>
{
PetName= p.Pet,
PetID= p.PetID
}
});

Kindly help me in getting the return object with couple of properties, one of the property as list.

Help is highly appreciated. Thanks.



Email address update for alerts

Continue reading...
 
Back
Top