question

krishnaramisetty-9724 avatar image
0 Votes"
krishnaramisetty-9724 asked ZhanglongWu-MSFT answered

How to fill object using c# linq

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

dotnet-csharp
image.png (19.4 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

cooldadtx avatar image
0 Votes"
cooldadtx answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

ZhanglongWu-MSFT avatar image
0 Votes"
ZhanglongWu-MSFT answered

Hi @krishnaramisetty-9724

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



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.