skip to Main Content

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 });
            }

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. you can use this code

    var query = _context1.dbset...
    
    var properties = JArray.FromObject(query).Select(j => ((JObject)j).Properties());
    
    List<List<object>> data = new List<List<object>> { properties.Select(ja => ja.Select(p => (object)p.Name).ToList()).First() };
    
    data.AddRange(properties.Select(ja => ja.Select(p => p.Value.ToObject<object>()).ToList()).ToList());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search