Creating a DataTable From a Linq Query in my C# Windows form












0















Creating a DataTable From a Linq Query
I use Ling to show my data on dataGridview and I have linq search funtion to search poeple. It's workin fine but not as Datatable do. I have to write the hole name before my serch function shoe me the name. I want to create Creat a DataTable From a Linq Query but I donät know how to do it.
Here is my code:



public void SerachdataEmp(string name)
{
db = new EmployeeEntity();
var result = (from u in db.Employee
join d in db.Department on u.DepartmentId equals d.DepartmentId
where u.FirstName == name
select new
{
FirstName = u.FirstName,
LastName = u.LastNameName,
DepartmentName = d.DepartmentName
}
}).Tolist();
dataGridView1.DataSource = result;


I tried like this



(from u in db.Employee.AsEnumerable()
join d in db.Department.AsEnumerable() on u.DepartmentId equals d.DepartmentId
where u.FirstName == searchEmployee

but then I don't know how to do. Thank you in advance!









share|improve this question























  • I believe DataGridView should support an anonymous type - what happens when you use your code?

    – NetMage
    Nov 21 '18 at 18:17











  • not as Datatable do What do you mean? You already have everything available to perform all kinds of searches. What does a DataTable add to that?

    – Gert Arnold
    Nov 21 '18 at 20:47











  • @Gert Arnold , thank you for your response. If I have a name with begining A or B then it shows me only if I write the hole name, it's not filtering in the begining.But if is Datatable with SqlConnecting , then I just need to input for example for "Johannes" I just need to input J then shows me all names who beginns with J before I put "Johannes". But right now I have to put "Johannes" to show me all pople who's name is Johannes. Sorry if I confuse you..;)

    – Helen Tekie
    Nov 22 '18 at 6:51











  • Look, a DataTable doesn't do anything. If you use it for selection queries it's the query that does the job. You just have a different query that contains something like StartsWith. You can do exactly the same thing in LINQ (u.FirstName.StartWith...)

    – Gert Arnold
    Nov 22 '18 at 8:59











  • @GertArnold Do you mean like this u.FirstName.StartsWith == username?

    – Helen Tekie
    Nov 22 '18 at 10:00


















0















Creating a DataTable From a Linq Query
I use Ling to show my data on dataGridview and I have linq search funtion to search poeple. It's workin fine but not as Datatable do. I have to write the hole name before my serch function shoe me the name. I want to create Creat a DataTable From a Linq Query but I donät know how to do it.
Here is my code:



public void SerachdataEmp(string name)
{
db = new EmployeeEntity();
var result = (from u in db.Employee
join d in db.Department on u.DepartmentId equals d.DepartmentId
where u.FirstName == name
select new
{
FirstName = u.FirstName,
LastName = u.LastNameName,
DepartmentName = d.DepartmentName
}
}).Tolist();
dataGridView1.DataSource = result;


I tried like this



(from u in db.Employee.AsEnumerable()
join d in db.Department.AsEnumerable() on u.DepartmentId equals d.DepartmentId
where u.FirstName == searchEmployee

but then I don't know how to do. Thank you in advance!









share|improve this question























  • I believe DataGridView should support an anonymous type - what happens when you use your code?

    – NetMage
    Nov 21 '18 at 18:17











  • not as Datatable do What do you mean? You already have everything available to perform all kinds of searches. What does a DataTable add to that?

    – Gert Arnold
    Nov 21 '18 at 20:47











  • @Gert Arnold , thank you for your response. If I have a name with begining A or B then it shows me only if I write the hole name, it's not filtering in the begining.But if is Datatable with SqlConnecting , then I just need to input for example for "Johannes" I just need to input J then shows me all names who beginns with J before I put "Johannes". But right now I have to put "Johannes" to show me all pople who's name is Johannes. Sorry if I confuse you..;)

    – Helen Tekie
    Nov 22 '18 at 6:51











  • Look, a DataTable doesn't do anything. If you use it for selection queries it's the query that does the job. You just have a different query that contains something like StartsWith. You can do exactly the same thing in LINQ (u.FirstName.StartWith...)

    – Gert Arnold
    Nov 22 '18 at 8:59











  • @GertArnold Do you mean like this u.FirstName.StartsWith == username?

    – Helen Tekie
    Nov 22 '18 at 10:00
















0












0








0








Creating a DataTable From a Linq Query
I use Ling to show my data on dataGridview and I have linq search funtion to search poeple. It's workin fine but not as Datatable do. I have to write the hole name before my serch function shoe me the name. I want to create Creat a DataTable From a Linq Query but I donät know how to do it.
Here is my code:



public void SerachdataEmp(string name)
{
db = new EmployeeEntity();
var result = (from u in db.Employee
join d in db.Department on u.DepartmentId equals d.DepartmentId
where u.FirstName == name
select new
{
FirstName = u.FirstName,
LastName = u.LastNameName,
DepartmentName = d.DepartmentName
}
}).Tolist();
dataGridView1.DataSource = result;


I tried like this



(from u in db.Employee.AsEnumerable()
join d in db.Department.AsEnumerable() on u.DepartmentId equals d.DepartmentId
where u.FirstName == searchEmployee

but then I don't know how to do. Thank you in advance!









share|improve this question














Creating a DataTable From a Linq Query
I use Ling to show my data on dataGridview and I have linq search funtion to search poeple. It's workin fine but not as Datatable do. I have to write the hole name before my serch function shoe me the name. I want to create Creat a DataTable From a Linq Query but I donät know how to do it.
Here is my code:



public void SerachdataEmp(string name)
{
db = new EmployeeEntity();
var result = (from u in db.Employee
join d in db.Department on u.DepartmentId equals d.DepartmentId
where u.FirstName == name
select new
{
FirstName = u.FirstName,
LastName = u.LastNameName,
DepartmentName = d.DepartmentName
}
}).Tolist();
dataGridView1.DataSource = result;


I tried like this



(from u in db.Employee.AsEnumerable()
join d in db.Department.AsEnumerable() on u.DepartmentId equals d.DepartmentId
where u.FirstName == searchEmployee

but then I don't know how to do. Thank you in advance!






c# linq datatable






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 15:26









Helen TekieHelen Tekie

1401110




1401110













  • I believe DataGridView should support an anonymous type - what happens when you use your code?

    – NetMage
    Nov 21 '18 at 18:17











  • not as Datatable do What do you mean? You already have everything available to perform all kinds of searches. What does a DataTable add to that?

    – Gert Arnold
    Nov 21 '18 at 20:47











  • @Gert Arnold , thank you for your response. If I have a name with begining A or B then it shows me only if I write the hole name, it's not filtering in the begining.But if is Datatable with SqlConnecting , then I just need to input for example for "Johannes" I just need to input J then shows me all names who beginns with J before I put "Johannes". But right now I have to put "Johannes" to show me all pople who's name is Johannes. Sorry if I confuse you..;)

    – Helen Tekie
    Nov 22 '18 at 6:51











  • Look, a DataTable doesn't do anything. If you use it for selection queries it's the query that does the job. You just have a different query that contains something like StartsWith. You can do exactly the same thing in LINQ (u.FirstName.StartWith...)

    – Gert Arnold
    Nov 22 '18 at 8:59











  • @GertArnold Do you mean like this u.FirstName.StartsWith == username?

    – Helen Tekie
    Nov 22 '18 at 10:00





















  • I believe DataGridView should support an anonymous type - what happens when you use your code?

    – NetMage
    Nov 21 '18 at 18:17











  • not as Datatable do What do you mean? You already have everything available to perform all kinds of searches. What does a DataTable add to that?

    – Gert Arnold
    Nov 21 '18 at 20:47











  • @Gert Arnold , thank you for your response. If I have a name with begining A or B then it shows me only if I write the hole name, it's not filtering in the begining.But if is Datatable with SqlConnecting , then I just need to input for example for "Johannes" I just need to input J then shows me all names who beginns with J before I put "Johannes". But right now I have to put "Johannes" to show me all pople who's name is Johannes. Sorry if I confuse you..;)

    – Helen Tekie
    Nov 22 '18 at 6:51











  • Look, a DataTable doesn't do anything. If you use it for selection queries it's the query that does the job. You just have a different query that contains something like StartsWith. You can do exactly the same thing in LINQ (u.FirstName.StartWith...)

    – Gert Arnold
    Nov 22 '18 at 8:59











  • @GertArnold Do you mean like this u.FirstName.StartsWith == username?

    – Helen Tekie
    Nov 22 '18 at 10:00



















I believe DataGridView should support an anonymous type - what happens when you use your code?

– NetMage
Nov 21 '18 at 18:17





I believe DataGridView should support an anonymous type - what happens when you use your code?

– NetMage
Nov 21 '18 at 18:17













not as Datatable do What do you mean? You already have everything available to perform all kinds of searches. What does a DataTable add to that?

– Gert Arnold
Nov 21 '18 at 20:47





not as Datatable do What do you mean? You already have everything available to perform all kinds of searches. What does a DataTable add to that?

– Gert Arnold
Nov 21 '18 at 20:47













@Gert Arnold , thank you for your response. If I have a name with begining A or B then it shows me only if I write the hole name, it's not filtering in the begining.But if is Datatable with SqlConnecting , then I just need to input for example for "Johannes" I just need to input J then shows me all names who beginns with J before I put "Johannes". But right now I have to put "Johannes" to show me all pople who's name is Johannes. Sorry if I confuse you..;)

– Helen Tekie
Nov 22 '18 at 6:51





@Gert Arnold , thank you for your response. If I have a name with begining A or B then it shows me only if I write the hole name, it's not filtering in the begining.But if is Datatable with SqlConnecting , then I just need to input for example for "Johannes" I just need to input J then shows me all names who beginns with J before I put "Johannes". But right now I have to put "Johannes" to show me all pople who's name is Johannes. Sorry if I confuse you..;)

– Helen Tekie
Nov 22 '18 at 6:51













Look, a DataTable doesn't do anything. If you use it for selection queries it's the query that does the job. You just have a different query that contains something like StartsWith. You can do exactly the same thing in LINQ (u.FirstName.StartWith...)

– Gert Arnold
Nov 22 '18 at 8:59





Look, a DataTable doesn't do anything. If you use it for selection queries it's the query that does the job. You just have a different query that contains something like StartsWith. You can do exactly the same thing in LINQ (u.FirstName.StartWith...)

– Gert Arnold
Nov 22 '18 at 8:59













@GertArnold Do you mean like this u.FirstName.StartsWith == username?

– Helen Tekie
Nov 22 '18 at 10:00







@GertArnold Do you mean like this u.FirstName.StartsWith == username?

– Helen Tekie
Nov 22 '18 at 10:00














2 Answers
2






active

oldest

votes


















0














instead use query.ToList();



use



 query.CopyToDataTable();





share|improve this answer
























  • That only works if query returns IEnumerable<DataRow> or a subclass of DataRow.

    – NetMage
    Nov 21 '18 at 18:09











  • @NetMage Thank you for respons, but How can I formulate then IEnumerable<DataRow>?

    – Helen Tekie
    Nov 21 '18 at 19:18











  • @Paulo , thank you for responce, but how should be look like my code then?

    – Helen Tekie
    Nov 21 '18 at 19:20











  • @HelenTekie I don't recommend that.

    – NetMage
    Nov 21 '18 at 20:16











  • @NetMage Thank. It's too complicated for me So I prefer to use SqlConnection. But my Project is buld by ADO:NET ENTITY DATA MODEL. So It's ok t oimplement two different Connection strings, One ADO.NET Entity and the other one SqlConnection System.Data.SqlClient ? Becouse When to use DataTable it work bete rwith SqlConnection. But is tha tnorma lto use two different Connections in one single Project?

    – Helen Tekie
    Nov 21 '18 at 21:11



















0














I don't recommend this, and I don't believe your search issue is with not using a DataTable, but using these extensions you can convert your query answer into a DataTable - just put ToDataTable() in place of ToList().



public static class ExtensionMethods {
// ***
// *** IEnumerable<> Extensions
// ***
public static DataTable ToDataTable<T>(this IEnumerable<T> rows) {
var dt = new DataTable();
if (rows.Any()) {
var rowType = typeof(T);
var memberInfos = rowType.GetPropertiesOrFields();
foreach (var info in memberInfos)
dt.Columns.Add(new DataColumn(info.Name, info.GetMemberType()));

foreach (var r in rows)
dt.Rows.Add(memberInfos.Select(i => i.GetValue(r)).ToArray());
}
return dt;
}

// ***
// *** MemberInfo Extensions
// ***
public static Type GetMemberType(this MemberInfo member) {
switch (member) {
case FieldInfo mfi:
return mfi.FieldType;
case PropertyInfo mpi:
return mpi.PropertyType;
case EventInfo mei:
return mei.EventHandlerType;
default:
throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", nameof(member));
}
}

public static object GetValue(this MemberInfo member, object srcObject) {
switch (member) {
case FieldInfo mfi:
return mfi.GetValue(srcObject);
case PropertyInfo mpi:
return mpi.GetValue(srcObject);
default:
throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", nameof(member));
}
}

// ***
// *** Type Extensions
// ***
public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field | mi.MemberType == MemberTypes.Property).ToList();
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415313%2fcreating-a-datatable-from-a-linq-query-in-my-c-sharp-windows-form%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    instead use query.ToList();



    use



     query.CopyToDataTable();





    share|improve this answer
























    • That only works if query returns IEnumerable<DataRow> or a subclass of DataRow.

      – NetMage
      Nov 21 '18 at 18:09











    • @NetMage Thank you for respons, but How can I formulate then IEnumerable<DataRow>?

      – Helen Tekie
      Nov 21 '18 at 19:18











    • @Paulo , thank you for responce, but how should be look like my code then?

      – Helen Tekie
      Nov 21 '18 at 19:20











    • @HelenTekie I don't recommend that.

      – NetMage
      Nov 21 '18 at 20:16











    • @NetMage Thank. It's too complicated for me So I prefer to use SqlConnection. But my Project is buld by ADO:NET ENTITY DATA MODEL. So It's ok t oimplement two different Connection strings, One ADO.NET Entity and the other one SqlConnection System.Data.SqlClient ? Becouse When to use DataTable it work bete rwith SqlConnection. But is tha tnorma lto use two different Connections in one single Project?

      – Helen Tekie
      Nov 21 '18 at 21:11
















    0














    instead use query.ToList();



    use



     query.CopyToDataTable();





    share|improve this answer
























    • That only works if query returns IEnumerable<DataRow> or a subclass of DataRow.

      – NetMage
      Nov 21 '18 at 18:09











    • @NetMage Thank you for respons, but How can I formulate then IEnumerable<DataRow>?

      – Helen Tekie
      Nov 21 '18 at 19:18











    • @Paulo , thank you for responce, but how should be look like my code then?

      – Helen Tekie
      Nov 21 '18 at 19:20











    • @HelenTekie I don't recommend that.

      – NetMage
      Nov 21 '18 at 20:16











    • @NetMage Thank. It's too complicated for me So I prefer to use SqlConnection. But my Project is buld by ADO:NET ENTITY DATA MODEL. So It's ok t oimplement two different Connection strings, One ADO.NET Entity and the other one SqlConnection System.Data.SqlClient ? Becouse When to use DataTable it work bete rwith SqlConnection. But is tha tnorma lto use two different Connections in one single Project?

      – Helen Tekie
      Nov 21 '18 at 21:11














    0












    0








    0







    instead use query.ToList();



    use



     query.CopyToDataTable();





    share|improve this answer













    instead use query.ToList();



    use



     query.CopyToDataTable();






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 21 '18 at 17:01









    PauloPaulo

    210110




    210110













    • That only works if query returns IEnumerable<DataRow> or a subclass of DataRow.

      – NetMage
      Nov 21 '18 at 18:09











    • @NetMage Thank you for respons, but How can I formulate then IEnumerable<DataRow>?

      – Helen Tekie
      Nov 21 '18 at 19:18











    • @Paulo , thank you for responce, but how should be look like my code then?

      – Helen Tekie
      Nov 21 '18 at 19:20











    • @HelenTekie I don't recommend that.

      – NetMage
      Nov 21 '18 at 20:16











    • @NetMage Thank. It's too complicated for me So I prefer to use SqlConnection. But my Project is buld by ADO:NET ENTITY DATA MODEL. So It's ok t oimplement two different Connection strings, One ADO.NET Entity and the other one SqlConnection System.Data.SqlClient ? Becouse When to use DataTable it work bete rwith SqlConnection. But is tha tnorma lto use two different Connections in one single Project?

      – Helen Tekie
      Nov 21 '18 at 21:11



















    • That only works if query returns IEnumerable<DataRow> or a subclass of DataRow.

      – NetMage
      Nov 21 '18 at 18:09











    • @NetMage Thank you for respons, but How can I formulate then IEnumerable<DataRow>?

      – Helen Tekie
      Nov 21 '18 at 19:18











    • @Paulo , thank you for responce, but how should be look like my code then?

      – Helen Tekie
      Nov 21 '18 at 19:20











    • @HelenTekie I don't recommend that.

      – NetMage
      Nov 21 '18 at 20:16











    • @NetMage Thank. It's too complicated for me So I prefer to use SqlConnection. But my Project is buld by ADO:NET ENTITY DATA MODEL. So It's ok t oimplement two different Connection strings, One ADO.NET Entity and the other one SqlConnection System.Data.SqlClient ? Becouse When to use DataTable it work bete rwith SqlConnection. But is tha tnorma lto use two different Connections in one single Project?

      – Helen Tekie
      Nov 21 '18 at 21:11

















    That only works if query returns IEnumerable<DataRow> or a subclass of DataRow.

    – NetMage
    Nov 21 '18 at 18:09





    That only works if query returns IEnumerable<DataRow> or a subclass of DataRow.

    – NetMage
    Nov 21 '18 at 18:09













    @NetMage Thank you for respons, but How can I formulate then IEnumerable<DataRow>?

    – Helen Tekie
    Nov 21 '18 at 19:18





    @NetMage Thank you for respons, but How can I formulate then IEnumerable<DataRow>?

    – Helen Tekie
    Nov 21 '18 at 19:18













    @Paulo , thank you for responce, but how should be look like my code then?

    – Helen Tekie
    Nov 21 '18 at 19:20





    @Paulo , thank you for responce, but how should be look like my code then?

    – Helen Tekie
    Nov 21 '18 at 19:20













    @HelenTekie I don't recommend that.

    – NetMage
    Nov 21 '18 at 20:16





    @HelenTekie I don't recommend that.

    – NetMage
    Nov 21 '18 at 20:16













    @NetMage Thank. It's too complicated for me So I prefer to use SqlConnection. But my Project is buld by ADO:NET ENTITY DATA MODEL. So It's ok t oimplement two different Connection strings, One ADO.NET Entity and the other one SqlConnection System.Data.SqlClient ? Becouse When to use DataTable it work bete rwith SqlConnection. But is tha tnorma lto use two different Connections in one single Project?

    – Helen Tekie
    Nov 21 '18 at 21:11





    @NetMage Thank. It's too complicated for me So I prefer to use SqlConnection. But my Project is buld by ADO:NET ENTITY DATA MODEL. So It's ok t oimplement two different Connection strings, One ADO.NET Entity and the other one SqlConnection System.Data.SqlClient ? Becouse When to use DataTable it work bete rwith SqlConnection. But is tha tnorma lto use two different Connections in one single Project?

    – Helen Tekie
    Nov 21 '18 at 21:11













    0














    I don't recommend this, and I don't believe your search issue is with not using a DataTable, but using these extensions you can convert your query answer into a DataTable - just put ToDataTable() in place of ToList().



    public static class ExtensionMethods {
    // ***
    // *** IEnumerable<> Extensions
    // ***
    public static DataTable ToDataTable<T>(this IEnumerable<T> rows) {
    var dt = new DataTable();
    if (rows.Any()) {
    var rowType = typeof(T);
    var memberInfos = rowType.GetPropertiesOrFields();
    foreach (var info in memberInfos)
    dt.Columns.Add(new DataColumn(info.Name, info.GetMemberType()));

    foreach (var r in rows)
    dt.Rows.Add(memberInfos.Select(i => i.GetValue(r)).ToArray());
    }
    return dt;
    }

    // ***
    // *** MemberInfo Extensions
    // ***
    public static Type GetMemberType(this MemberInfo member) {
    switch (member) {
    case FieldInfo mfi:
    return mfi.FieldType;
    case PropertyInfo mpi:
    return mpi.PropertyType;
    case EventInfo mei:
    return mei.EventHandlerType;
    default:
    throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", nameof(member));
    }
    }

    public static object GetValue(this MemberInfo member, object srcObject) {
    switch (member) {
    case FieldInfo mfi:
    return mfi.GetValue(srcObject);
    case PropertyInfo mpi:
    return mpi.GetValue(srcObject);
    default:
    throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", nameof(member));
    }
    }

    // ***
    // *** Type Extensions
    // ***
    public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
    t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field | mi.MemberType == MemberTypes.Property).ToList();
    }





    share|improve this answer




























      0














      I don't recommend this, and I don't believe your search issue is with not using a DataTable, but using these extensions you can convert your query answer into a DataTable - just put ToDataTable() in place of ToList().



      public static class ExtensionMethods {
      // ***
      // *** IEnumerable<> Extensions
      // ***
      public static DataTable ToDataTable<T>(this IEnumerable<T> rows) {
      var dt = new DataTable();
      if (rows.Any()) {
      var rowType = typeof(T);
      var memberInfos = rowType.GetPropertiesOrFields();
      foreach (var info in memberInfos)
      dt.Columns.Add(new DataColumn(info.Name, info.GetMemberType()));

      foreach (var r in rows)
      dt.Rows.Add(memberInfos.Select(i => i.GetValue(r)).ToArray());
      }
      return dt;
      }

      // ***
      // *** MemberInfo Extensions
      // ***
      public static Type GetMemberType(this MemberInfo member) {
      switch (member) {
      case FieldInfo mfi:
      return mfi.FieldType;
      case PropertyInfo mpi:
      return mpi.PropertyType;
      case EventInfo mei:
      return mei.EventHandlerType;
      default:
      throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", nameof(member));
      }
      }

      public static object GetValue(this MemberInfo member, object srcObject) {
      switch (member) {
      case FieldInfo mfi:
      return mfi.GetValue(srcObject);
      case PropertyInfo mpi:
      return mpi.GetValue(srcObject);
      default:
      throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", nameof(member));
      }
      }

      // ***
      // *** Type Extensions
      // ***
      public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
      t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field | mi.MemberType == MemberTypes.Property).ToList();
      }





      share|improve this answer


























        0












        0








        0







        I don't recommend this, and I don't believe your search issue is with not using a DataTable, but using these extensions you can convert your query answer into a DataTable - just put ToDataTable() in place of ToList().



        public static class ExtensionMethods {
        // ***
        // *** IEnumerable<> Extensions
        // ***
        public static DataTable ToDataTable<T>(this IEnumerable<T> rows) {
        var dt = new DataTable();
        if (rows.Any()) {
        var rowType = typeof(T);
        var memberInfos = rowType.GetPropertiesOrFields();
        foreach (var info in memberInfos)
        dt.Columns.Add(new DataColumn(info.Name, info.GetMemberType()));

        foreach (var r in rows)
        dt.Rows.Add(memberInfos.Select(i => i.GetValue(r)).ToArray());
        }
        return dt;
        }

        // ***
        // *** MemberInfo Extensions
        // ***
        public static Type GetMemberType(this MemberInfo member) {
        switch (member) {
        case FieldInfo mfi:
        return mfi.FieldType;
        case PropertyInfo mpi:
        return mpi.PropertyType;
        case EventInfo mei:
        return mei.EventHandlerType;
        default:
        throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", nameof(member));
        }
        }

        public static object GetValue(this MemberInfo member, object srcObject) {
        switch (member) {
        case FieldInfo mfi:
        return mfi.GetValue(srcObject);
        case PropertyInfo mpi:
        return mpi.GetValue(srcObject);
        default:
        throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", nameof(member));
        }
        }

        // ***
        // *** Type Extensions
        // ***
        public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
        t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field | mi.MemberType == MemberTypes.Property).ToList();
        }





        share|improve this answer













        I don't recommend this, and I don't believe your search issue is with not using a DataTable, but using these extensions you can convert your query answer into a DataTable - just put ToDataTable() in place of ToList().



        public static class ExtensionMethods {
        // ***
        // *** IEnumerable<> Extensions
        // ***
        public static DataTable ToDataTable<T>(this IEnumerable<T> rows) {
        var dt = new DataTable();
        if (rows.Any()) {
        var rowType = typeof(T);
        var memberInfos = rowType.GetPropertiesOrFields();
        foreach (var info in memberInfos)
        dt.Columns.Add(new DataColumn(info.Name, info.GetMemberType()));

        foreach (var r in rows)
        dt.Rows.Add(memberInfos.Select(i => i.GetValue(r)).ToArray());
        }
        return dt;
        }

        // ***
        // *** MemberInfo Extensions
        // ***
        public static Type GetMemberType(this MemberInfo member) {
        switch (member) {
        case FieldInfo mfi:
        return mfi.FieldType;
        case PropertyInfo mpi:
        return mpi.PropertyType;
        case EventInfo mei:
        return mei.EventHandlerType;
        default:
        throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", nameof(member));
        }
        }

        public static object GetValue(this MemberInfo member, object srcObject) {
        switch (member) {
        case FieldInfo mfi:
        return mfi.GetValue(srcObject);
        case PropertyInfo mpi:
        return mpi.GetValue(srcObject);
        default:
        throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", nameof(member));
        }
        }

        // ***
        // *** Type Extensions
        // ***
        public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
        t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field | mi.MemberType == MemberTypes.Property).ToList();
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 20:18









        NetMageNetMage

        13.7k12036




        13.7k12036






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415313%2fcreating-a-datatable-from-a-linq-query-in-my-c-sharp-windows-form%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Hercules Kyvelos

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud