nav100
nav100

Reputation: 411

DataTable select help

I am trying to convert datatable to List. Could you please help me with the query?

         var result = DataTable1.AsEnumerable().Select(e => {e.Field<int>("MID"), e.Field<string>("MTX")}).ToList();
        JavaScriptSerializer ser = new JavaScriptSerializer();
        string json = ser.Serialize(result);

Thank you..

Upvotes: 0

Views: 214

Answers (3)

Anthony Pegram
Anthony Pegram

Reputation: 126804

You need to provide names for the properties inside your Select call. These names will not automatically and unambiguously resolve in this particular case. Try

var result = DataTable1.AsEnumerable().Select(row => new { Mid = row.Field<int>("Mid"), MTX = row.Field<string>("MTX") });
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(result);

Those names will then become part of the json result. Such as

[{"Mid":1,"MTX":"A"},{"Mid":2,"MTX":"B"}]

Upvotes: 1

Alex J
Alex J

Reputation: 10205

Try:

var result = DataTable1.AsEnumerable()
    .Select(e => new object[] { e.Field<int>("MID"), e.Field<string>("MTX") })
    .ToList();

Upvotes: 0

John K.
John K.

Reputation: 5474

IEnumerable<DataRow> sequence = dt.AsEnumerable(); 

or

List<DataRow> list = dt.AsEnumerable().ToList(); 

Upvotes: 0

Related Questions