kartoos khan
kartoos khan

Reputation: 449

Convert Datatable to nested list/object using C#

I have a datatable as this. enter image description here 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

Upvotes: 0

Views: 2176

Answers (1)

user1672994
user1672994

Reputation: 10849

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.

Upvotes: 1

Related Questions