Home > Enterprise >  how can i add column names at 1st row of list?
how can i add column names at 1st row of list?

Time:01-22

I have a basic linq that gets 10 rows from database; get 2 columns (First_Name & Last_Name) from database. - this works ok

Question - how can i add column names at 1st row of list?

var query = _context1.dbset
                     .Select(x =>
                           new
                           {
                               First_Name = x.First_Name,
                               Last_Name = x.Last_Name
                           }).Take(10).ToList();

What I tried. Below works good but I have to manually type all column names and also when adding data in for loop `

            List<object> chartData = new List<object>();
            data .Add(new object[] { "First_Name", "Last_Name" });
            foreach (var item in query)
            {
               Data.Add(new object[] { item.First_Name, item.Last_Name });
            }

CodePudding user response:

Use reflection:

var query = _context1.dbset
                 .Select(x =>
                       new
                       {
                           First_Name = x.First_Name,
                           Last_Name = x.Last_Name
                       }).Take(10).ToList();

var columnNames = query[0].GetType().GetProperties().Select(p => p.Name).ToArray();

var result = new List<object> { columnNames };
result.AddRange(query);

CodePudding user response:

you can use this code

var query = _context1.dbset...

var ja = JArray.FromObject(query);

List<object> names = ja.Select(j => ((JObject)j).Properties()
              .Select(p => (object) p.Name ).ToArray()).First().ToList();

List<List<object>> data = ja.Select(j => ((JObject)j).Properties()
               .Select(p => p.Value.ToObject<object>()).ToList()).ToList();

data.Insert(0, names);

string firstItem = (string) data[0][0]; //FirstName
  • Related