0

I have a class:

public class MyClass
{
    public uint ID { get; set; }
    public List<double> Values { get; set; }
}

Then, I'm creating a list of class objects:

List<MyClass> objects = new List<MyClass>(); // then I add the data to this list

Now, I'm need to select data from objects like:

var query = objects.Select(o => new { o.ID, o.Values } ).ToList(); // this example show only ID field in DataTable

and convert result to DataTable like this:

public DataTable ConvertToDataTable<T>(IList<T> data)
{
    DataTable table = new DataTable();
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));          

    foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

    foreach (T item in data)
    {
        DataRow row = table.NewRow();

        foreach (PropertyDescriptor prop in properties)
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;

        table.Rows.Add(row);
    }

    return table;
}

So, I need to make something like cross-tab query. How can I doing that?

Vlad i Slav
  • 59
  • 2
  • 12
  • 1
    1. there are extensions https://learn.microsoft.com/en-us/dotnet/api/system.data.datatableextensions.copytodatatable?view=netframework-4.7.2 2. Why not Linq-to-objects 3. Linq to data-table – T.S. Dec 14 '18 at 04:26
  • @T.S. Please, show example. – Vlad i Slav Dec 14 '18 at 04:49
  • Few different ways to pivot are given: https://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq – peeyush singh Dec 14 '18 at 04:49
  • @peeyush singh, thank's, but this link does not contains examples with List as class field or List into another List, so this is not work for me. – Vlad i Slav Dec 14 '18 at 05:35
  • Your `query` is just a copy of the original `List` in an anonymous class - what are you really trying to do? – NetMage Dec 14 '18 at 19:13
  • @NetMage, of course, my class have more fields, than I showed here, but I need to select only two of it. – Vlad i Slav Dec 14 '18 at 22:52
  • Vlad, if you're looking for examples - your question is invalid because now it falls under category: looking for tutorials, books, references, etc. This is what google is for – T.S. Dec 14 '18 at 23:33
  • @T.S., thank's, but if I found a solution in Google, I would not ask this question. – Vlad i Slav Dec 15 '18 at 00:50

0 Answers0