DataTable select help - c#

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..

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"}]

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

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

Related

C# items as root nodes of JSON

I'm trying to pass a Json that I'd like to access from jquery as,
jdata.comType
my c# code is,
var frontChartList = new List<object>();
frontChartList.Add(new
{
comType = comType,
today = DateTime.Now.ToString("D"),
agentsAdded = "53",
agentsAvail = "47",
packageAvailDays = leftDays.ToString(),
});
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(frontChartList);
return json;
I cannot access this as
jdata.comType
only as,
jdata[0].comType
how should I create the JSON to get a string accessible as jdata.comType?
since I will only be passing one object in this.
Because your frontChartList is a List<object>, change it to single object instead:
var frontChartList = new
{
comType = comType,
today = DateTime.Now.ToString("D"),
agentsAdded = "53",
agentsAvail = "47",
packageAvailDays = leftDays.ToString(),
});

Append items to an object

I have created a Linq statement to get a list of items from the database. So I need to loop trough the query and append to object to then serialize to then be able to use as json in javascript. The problem is I cannot append to the declared object 'obj'. Can anyone help??
DataContext dataContext = new DataContext();
var query = from qr in dataContext.tblStocks
where qr.enable == true
select qr;
var obj = new JObject();
foreach (var item in query)
{
//obj = new JObject();
obj = ( new JObject(
new JProperty("stockID",item.stockID),
new JProperty("itemDepartmentID", item.itemDepartmentID),
new JProperty("item" , item.item),
new JProperty("description", item.description),
new JProperty("stockAmount", item.stockAmount),
new JProperty("priceExlVat", item.priceExlVat),
new JProperty("vat", item.vat),
new JProperty("priceIncVAT", item.priceIncVAT),
new JProperty("upc1", item.upc1),
new JProperty("upc2", item.upc2)
));
}
var serialized = JsonConvert.SerializeObject(obj);
return serialized;
You are reassigning obj each time through the loop hence all other data will be lost.
Easier to create an array:
obj = new JArray();
foreach (var item in query) {
obj.Add(new JObject(
new JProperty(...),
...));
}
Why don't you just serialize your object?
List<dynamic> obj = new List<dynamic>();
foreach(var item in query) {
obj.Add(new
{
itemDepartmentID = item.itemDepartmentID,
description = item.description,
...
});
}
var serialized = JsonConvert.SerializeObject(obj);
Alternative you could use an anonymous type in the query and just serialize the entire query for the query returns an IEnumerable<T> and this is converted automatically to an jsonArray:
DataContext dataContext = new DataContext();
var query = dataContext.tblStocks
.Where(stockItem => stockItem.enable)
.Select(stockItem => new
{
stockItem.stockID,
stockItem.itemDepartmentID,
stockItem.item,
stockItem.description,
stockItem.stockAmount,
stockItem.priceExlVat,
stockItem.vat,
stockItem.priceIncVat,
stockItem.upc1,
stockItem.upc2
});
return JsonConvert.SerializeObject(query);

C#, JSON: Join two array to use JSON

Can you help me to resolve this proplem. I will use JSON with Name and Description and want to merge two array.
var listCateogries = categories.Select(x => new
{
Name = x.Name,
Description = x.Description
});
var listProducts = products.Select(x => new
{
Name = x.Name,
Description = x.Details
});
var data = listCateogries + listProducts;
Thanks you very much.
Try Enumerable.Concat
var data = listCateogries.Concat(listProducts);

hashtable keys from multiple objects in linq

Hashtable mainhash = new Hashtable();
testdata td = new testdata() { value = "td" };
td.hash.Add("1", "tdvalue1");
td.hash.Add("2", "tdvalue2");
td.hash.Add("3", "tdvalue3");
td.hash.Add("4", "tdvalue4");
td.hash.Add("5", "tdvalue5");
testdata td1 = new testdata() { value = "td1" };
td1.hash.Add("1", "td1value1");
td1.hash.Add("2", "td1value2");
td1.hash.Add("3", "td1value3");
td1.hash.Add("4", "td1value4");
td1.hash.Add("5", "td1value5");
testdata td2 = new testdata() { value = "td2" };
td2.hash.Add("1", "td2value1");
td2.hash.Add("2", "td2value2");
td2.hash.Add("3", "td2value3");
td2.hash.Add("4", "td2value4");
td2.hash.Add("5", "td2value5");
testdata td3 = new testdata() { value = "td3" };
td3.hash.Add("1", "td3value1");
td3.hash.Add("2", "td3value2");
td3.hash.Add("3", "td3value3");
td3.hash.Add("4", "td3value4");
td3.hash.Add("5", "td3value5");
testdata td4 = new testdata() { value = "td4" };
td4.hash.Add("1", "td4value1");
td4.hash.Add("2", "td4value2");
td4.hash.Add("3", "td4value3");
td4.hash.Add("4", "td4value4");
td4.hash.Add("5", "td4value5");
mainhash.Add(1, td);
mainhash.Add(2, td1);
mainhash.Add(3, td2);
mainhash.Add(4, td3);
mainhash.Add(5, td4);
how to select all the keys using SelectMany by Linq into one list??
what i need to do in this??
var values = mainhash.Values.Cast<testdata>().Select(x => x.hash)
.SelectMany(x=> x.Keys);
what is wrong in this??
It doesn't know the type to use from Hashtable.Keys.
Try:
var values = mainhash.Values.Cast<testdata>().Select(x => x.hash)
.SelectMany(x => x.Keys.Cast<string>());
But better: use Dictionary<TKey,TValue> instead of Hashtable.
try below query -
var values = mainhash.Values.Cast<testdata>().SelectMany(x => x.hash.Keys.Cast<string>());
But, use dictionary instead of hashtable. It actually reduce the overhead of casting the objects.
hope above code helps you !!

c# find keywords in a list and create new list from the found items

i am learning c# and have the following problem, i can not find a solution.
the code i am trying is:
string theString = "aaa XXX,bbb XXX,ccc XXX,aaa XXX";
List<string> listFromTheString= new List<string>(theString.Split(','));
List<string> listOfFoundItems = new List<string>();
for (int i = 0; i < (listFromTheString.Count); i++)
{
if(listFromTheString[i].Contains("aaa"))
{
listOfFoundItems.Add(listFromTheString[i]);
}
}
I would like to iterate through the list and create new items in a new list if a special keyword is found. The list listOfFoundItems does not get filled with the founds.
can you please give me a hint what i am doing wrong?
You can accomplish this more succinctly with LINQ:
string theString = ("aaa XXX,bbb XXX,ccc XXX,aaa XXX");
List<string> listFromTheString = new List<string>(theString.Split(','));
List<string> listOfFoundItems = listFromTheString.Where(s => s.Contains("aaa")).ToList();
The code you provided does work, though.
Here's an alternate, one-line version:
List<string> listOfFoundItems = theString.Split(',').Where(s => s.Contains("aaa")).ToList();
theString.Split(',').Where(p=>p.Contains("aaa")).ToList()
I know you want to fix your algorithm, but once you do, consider grokking this expression:
listofFoundItems = (from s in theString.Split(',')
where s.Contains("aaa")
select s).ToList();
The code you provide works fine. Given that, I suspect you may be having some string comparison issues.
This code may work better for you:
const string given = "aaa XXX,bbb XXX,ccc XXX,aaa XXX";
var givenSplit = new List<string>(given.Split(','));
var listOfFoundItems = new List<string>();
foreach(var item in givenSplit.Where(g => g.IndexOf("aAa", StringComparison.InvariantCultureIgnoreCase) > -1))
{
listOfFoundItems.Add(item);
}
// two items are added
string theString = ("aaa XXX,bbb XXX,ccc XXX,aaa XXX");
List<string> listFromTheString = new List<string>(theString.Split(','));
List<string> listOfKeywords = new List<string> { "aaa" };
List<string> found = (from str in listFromTheString
where listOfKeywords.Any(keyword => str.Contains(keyword))
select str).ToList<string>();

Categories