I'm trying to retrieve a username
from a DataTable
by UserID
using LINQ
using this example.
//Example 1:
var user = (from dr in users.AsEnumerable()
where dr.Field<int>("UserID") == 2
select dr).First();
//Example 2:
string user = (from dr in users.AsEnumerable()
where dr.Field<int>("UserID") == 3
select dr.Field<string>("UserName")).First();
The above two examples are causing this cast error:
System.InvalidCastException: 'Specified cast is not valid.'
However, the query does work if my where clause
searches by string
instead of int
.
string result = (from row in users.AsEnumerable()
where row.Field<string>("UserName") == "TUser"
select row.Field<string>("UserName")).First();
How do I retrieve the single username by userid?
UPDATE:
Not sure if it's relevant, but the datatable is getting populated by desirializing .json
file using JSON.NET
A sample .json
[{ "UserID": 2, "UserName": "User", "StatusID": 1, "CreateDate": "2018-04-25T14:02:00", "CreateBy": "Admin", "ID": "9855626A-FEF1-4936-9EF6-DD896F80AE35" }, { "UserID": 3, "UserName": "TUser", "StatusID": 1, "CreateDate": "2018-04-25T14:02:00", "CreateBy": "Admin", "ID": "928D6099-0665-4FC8-BE4C-8E145E56E8BF" } ]
And populating datatable:
DataTable users = JsonConvert.DeserializeObject<DataTable>(File.ReadAllText(userPath));