Creating a DataTable From a Linq Query in my C# Windows form
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
add a comment |
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
I believeDataGridView
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 likeStartsWith
. 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
add a comment |
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
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
c# linq datatable
asked Nov 21 '18 at 15:26
Helen TekieHelen Tekie
1401110
1401110
I believeDataGridView
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 likeStartsWith
. 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
add a comment |
I believeDataGridView
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 likeStartsWith
. 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
add a comment |
2 Answers
2
active
oldest
votes
instead use query.ToList();
use
query.CopyToDataTable();
That only works ifquery
returnsIEnumerable<DataRow>
or a subclass ofDataRow
.
– 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
|
show 2 more comments
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();
}
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
instead use query.ToList();
use
query.CopyToDataTable();
That only works ifquery
returnsIEnumerable<DataRow>
or a subclass ofDataRow
.
– 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
|
show 2 more comments
instead use query.ToList();
use
query.CopyToDataTable();
That only works ifquery
returnsIEnumerable<DataRow>
or a subclass ofDataRow
.
– 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
|
show 2 more comments
instead use query.ToList();
use
query.CopyToDataTable();
instead use query.ToList();
use
query.CopyToDataTable();
answered Nov 21 '18 at 17:01
PauloPaulo
210110
210110
That only works ifquery
returnsIEnumerable<DataRow>
or a subclass ofDataRow
.
– 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
|
show 2 more comments
That only works ifquery
returnsIEnumerable<DataRow>
or a subclass ofDataRow
.
– 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
|
show 2 more comments
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();
}
add a comment |
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();
}
add a comment |
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();
}
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();
}
answered Nov 21 '18 at 20:18
NetMageNetMage
13.7k12036
13.7k12036
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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