How to fill object using c# linq

krishna ramisetty 21 Reputation points
2021-07-15T13:22:08.273+00:00

Hello Everyong,

i have below datatable and below models. i need to fill each CenterList with respectives CenterInfo list usig c# linq. can someone pls help me how to do this

115087-image.png

public class CenterList  
    {  
        public List<CenterInfo> centers;  
        public int CenterID { get; set; }  
        public int SupervisorID { get; set; }  
    }  
  
public class CenterInfo  
    {  
        public string CenterName;  
        public string CenterLocation;  
    }  

Thanks,
Krish

Developer technologies C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 60,161 Reputation points
    2021-07-15T13:31:09.027+00:00

    This isn't a job for LINQ. LINQ is for querying data whether that is in the DB or in memory.

    What data access technology are you using? If you're using EntityFramework or nHibernate or another ORM then they provide instructions on how to load data from a DB into memory. In some cases, like EF, then you can use LINQ to manipulate the results before coming back from the DB. Refer to this tutorial on how to set up EF to read your data from a database.

    If you are using ADO.NET datasets then you'll be using a data adapter's Fill method in combination with a Command to get the data. Then you can use LINQ to filter the results but in most cases it is better to do as much filtering on the DB side as possible first.

    If you're instead using ADO.NET data readers then you'll only need a Command. Refer to this tutorial for how to read data using ADO.NET.

    0 comments No comments

  2. Anonymous
    2021-08-10T08:23:15.433+00:00

    Hi @krishna ramisetty

    You can try the get the data from database by using entity framework core, then you can try the Linq as below:

    var result = listdetail.GroupBy(t => t.CenterID).Select(t => new CenterList()  
                {  
                    CenterID = t.Key,  
                    centers = listdetail.Where(x => x.CenterID == t.Key).Select(c => new CenterInfo() { CenterName = c.CenterName, CenterLocation = c.CenterLocation }).ToList(),  
                    SupervisorID = listdetail.Where(x => x.CenterID == t.Key).Select(c=> c.SupervisorID).FirstOrDefault()  
      
                }).ToList();  
    

    Best regards,
    Zhanglong

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.