简体   繁体   中英

Convert Datatable to nested list/object using C#

I have a datatable as this. 在此处输入图像描述 and data model as

public class Details
    {

        public String Id { get; set; }
        public String Type { get; set; }
        public String Name { get; set; }
        public String Terms { get; set; }
        public List<FAQ> Faqs { get; set; }
    }

    public class FAQ
    {
        public string Question { get; set; }
        public string Answer { get; set; }
    }

I want to convert it to a list type of details like List<Details> detatilsList; I tried like this but the rows are repeating. If i remove Details than I get distinct result but cant convert it to Details type due to anonymous cast exception

 var details = dt.AsEnumerable().GroupBy(x =>
                new Details //removing this detail gives distinct record as expected. But can not cast
                {
                    ID= x.Field<decimal>("ID"),
                    NAME = x.Field<string>("NAME"),
                    TYPE = x.Field<string>("TYPE"),
                    TERMS = x.Field<string>("TERMS")
                })
            .Select(x =>
                new
                {
                    x.Key.ID,
                    x.Key.NAME,
                    x.Key.TYPE,
                    x.Key.TERMS,
                    Faqs =
                    x.Select(
                        s => new Faq {Question = s.Field<string>("QUESTION"), Answer = s.Field<string>("ANSWER")})

                }).ToList();

How can i fix it and convert it to List of Details

You can group By by anonymous object for multiple keys then select the required columns from DataTable

The below code first groups the data using ID , Name , Type and Terms and later in Select clause, creates new Details object.

 var details = dt.AsEnumerable().GroupBy(x =>
            new
            {
                ID= x.Field<decimal>("ID"),
                NAME = x.Field<string>("NAME"),
                TYPE = x.Field<string>("TYPE"),
                TERMS = x.Field<string>("TERMS")
            })
        .Select(x =>
            new Details
            {
                x.Key.ID,
                x.Key.NAME,
                x.Key.TYPE,
                x.Key.TERMS,
                Faqs =
                x.Select(
                    s => new Faq {Question = s.Field<string>("QUESTION"), Answer = s.Field<string>("ANSWER")}).ToList()
            }).ToList();

Another point, if Id itself is unique then you don't need to group by multiple columns, you can group by ID only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM