Multi series JSON data for Google Charts - c#

I am trying to create a JSON feed to return to Google charts a multi line chart, with four series. I am struggling to form the correct JSON to return to the charts.
I am using a stored procedure that produces a long list of the data I require to show in the chart. I want to be able to take the long list of data and convert it into four separate data series and send back to the chart in JSON.
My Model:
public class FoodCountCompare
{
[JsonProperty("Count")]
public int Count { get; set; }
[JsonProperty("Day")]
public string Day { get; set; }
[JsonProperty("Type")]
public string Type { get; set; }
}
My SPROC:
SELECT COUNT(P) AS 'Count', DATENAME(DW, fldTimeStamp) AS 'Day', #P AS 'Type' FROM [dbname].[FoodTypes] WHERE Protein = 1 AND fldUserId = ''+ #UserId+'' GROUP BY DATENAME(DW, fldTimeStamp)
UNION ALL
SELECT COUNT(H) AS 'Count', DATENAME(DW, fldTimeStamp) AS 'Day', #H AS 'Type' FROM [dbname].[FoodTypes]WHERE HEC = 1 AND fldUserId = ''+ #UserId+'' GROUP BY DATENAME(DW, fldTimeStamp)
UNION ALL
SELECT COUNT(L) AS 'Count', DATENAME(DW, fldTimeStamp) AS 'Day', #L AS 'Type' FROM [dbname].[FoodTypes]WHERE LEC = 1 AND fldUserId = ''+ #UserId+'' GROUP BY DATENAME(DW, fldTimeStamp)
UNION ALL
SELECT COUNT(O) AS 'Count', DATENAME(DW, fldTimeStamp) AS 'Day', #F AS 'Type' FROM [dbname].[FoodTypes]WHERE OmegaFA = 1 AND fldUserId = ''+ #UserId+'' GROUP BY DATENAME(DW, fldTimeStamp)
In my C# code I am then creating four separate lists, which I am sure is wrong. Each list contains the correct data, so this part works. I have tried playing around with arrays and serializations, but I am stuck on how to take this further.
[Function(Name = "[dbname].[FoodCountCompare]")]
public List<FoodCountCompare> GetFoodCountCompare(){
string UserId = User.Identity.GetUserId();
var dc = new DataClasses1DataContext();
var x = dc.FoodCountCompare(UserId).ToList();
var Protein = (from a in x where a.Type == "P" select new { a.Count, a.Day, a.Type }).ToList();
var HEC = (from a in x where a.Type == "H" select new { a.Count, a.Day, a.Type }).ToList();
var LEC = (from a in x where a.Type == "L" select new { a.Count, a.Day, a.Type }).ToList();
var F = (from a in x where a.Type == "O" select new { a.Count, a.Day, a.Type }).ToList();
//Add code to create JSON here
JavaScriptSerializer js = new JavaScriptSerializer();
string p = js.Serialize(Protein);
string h = js.Serialize(HEC);
string l = js.Serialize(LEC);
string f = js.Serialize(F);
return something_like_json;
}
public JsonResult FoodCountCompare(){
var items = new List<FoodCountCompare>(GetFoodCountCompare());
return Json(items, JsonRequestBehavior.AllowGet);
}
For me the question is, how do you take this data and turn it into JSON, such a a nested array or straight set of data.

You mean something like:
[Function(Name = "[dbname].[FoodCountCompare]")]
public List<FoodCountCompare> GetFoodCountCompare(){
string UserId = User.Identity.GetUserId();
var dc = new DataClasses1DataContext();
var x = dc.FoodCountCompare(UserId).ToList();
var items = x.Select(d => new FoodCountCompare { Type = d.Type, Day = d.Day, Count = d.Count })
return items;
}
public JsonResult FoodCountCompare(){
var items = new List<FoodCountCompare>(GetFoodCountCompare());
return Json(new {
Protein = items.Where(d => d.Type == "P"),
Hec = items.Where(d => d.Type == "H"),
Lec = items.Where(d => d.Type == "L"),
F = items.Where(d => d.Type == "O"),
}, JsonRequestBehavior.AllowGet);
}
Which will result in 4 different arrays for each type:
{"Protein":[ ... ],"Hec":[ ... ], "Lec":[ ... ], "F":[ ... ]}
I believe you don't need to specify the exact json property names.

Related

Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#6>' to 'decimal'

hallo i have a linq query like this :
var data = from d in db.DailyBonus
where d.Date>= startDate1 && d.Date<=endDate1
group d by new { Em = d.Employee.Id } into g
select new BasisViewModel
{
EmployeeId = g.Key.Em,
EmployeeNumber = g.FirstOrDefault().Employee.EmployeeNumber,
FullName = g.FirstOrDefault().Employee.FullName,
HK1 = (decimal)g.FirstOrDefault().ManDays,
Basis1 = (decimal)g.FirstOrDefault().BonusBase,
HK2 = (
(from d in db.DailyBonus
where d.Date>= startDate2 && d.Date<=endDate2
group d by new { Em = d.Employee.Id } into g2
select new
{
Mandays = g.FirstOrDefault().ManDays <-- this is decimal type
}
),
};
the problem is , i just want to select one record for HK2 and assigned to Mandays in subquery but there is an error bellow :
Cannot implicitly convert type
'System.Linq.IQueryable' to 'decimal'
what is the solution ? thank you
Instead of returning an anonymous class (new {...})
select new
{
Mandays = g.FirstOrDefault().ManDays <-- this is decimal type
}
return a Decimal you want:
select g.FirstOrDefault().ManDays;
You should add another FirstOrDefault() in the end and use simple value instead of anonymous type:
var data = from d in db.DailyBonus
where d.Date>= startDate1 && d.Date<=endDate1
group d by new { Em = d.Employee.Id } into g
select new BasisViewModel
{
EmployeeId = g.Key.Em,
EmployeeNumber = g.FirstOrDefault().Employee.EmployeeNumber,
FullName = g.FirstOrDefault().Employee.FullName,
HK1 = (decimal)g.FirstOrDefault().ManDays,
Basis1 = (decimal)g.FirstOrDefault().BonusBase,
HK2 = (
(from d in db.DailyBonus
where d.Date>= startDate2 && d.Date<=endDate2
group d by new { Em = d.Employee.Id } into g2
select g.FirstOrDefault().ManDays <-- this is simple value now
).FirstOrDefault(),<--this is another first or default
};

Retrurn list of objects matching by property

I have a method for parsing XML:
public static List<Profile> Parse XML(string Document)
{
List<Profile> Result = new List<Profile>();
doc = XDocument.Load(Document);
Resoults = (from n in doc.Descendants("level")
select new Profile()
{
CurrentID = int.Parse(n.Attribute("CurrentID").Value),
Location = (from l in n.Element("ID").Elements("ID")
select new Location()
{
id = (int)(l.Attribute("id")),
x = (Single)l.Attribute("x"),
y = (Single)l.Attribute("y"),
z = (Single)l.Attribute("z")
}).ToList(),
Bank = (from l in doc.Descendants("Banker")
select new Banker()
{
BankID = (int)(l.Attribute("id")),
BankX = (Single)(l.Attribute("x")),
BankY = (Single)(l.Attribute("y")),
BankZ = (Single)(l.Attribute("z"))
}).ToList(),
Vendor = (from l in doc.Descendants("Vendor")
select new Vendor()
{
VendorID = (int)(l.Attribute("id")),
VendorX = (Single)(l.Attribute("x")),
VendorY = (Single)(l.Attribute("y")),
VendorZ = (Single)(l.Attribute("z"))
}).ToList()
}).ToList();
var ProperID = Resoults.Where(s => s.CurrentID <= 10).Aggregate((c, d) => c.CurrentID > d.CurrentID ? c : d);
return ProperID; //error: Here i want to return list ProperID
}
I want to parse XML file and then get node out of parsed list with specific CurrentID.
I want to return ProperID list but compiler errores out with:
Cannot implicitly convert type 'Classes.XMLprofile.Profile' to 'System.Collections.Generic.List<Classes.XMLprofile.Profile>'
You want return Results that have proper id in CurrentId,
In code you got compiler error because of return value is a Profile object and method signature is a List of Profile objects, So:
return Resoults.Where(p=>p.CurrentID ==ProperID.CurrentID).ToList();

Split linq join query in two selected lists and use Tuple to return the two lists

Have the following code: a entity linq query results in a select of two tables.
All data is available in the query, but can't get the result to split into two lists.
public Tuple<List<sale>, List<product>> SearchProduct(int productId = -1, string searchProduct = "")
{
//ToDo: searchProduct not working...gives nothing
var companyId = DalSession.DalGetCurrentUser().Company_ID;
using (var entity = new secondsoftEntities())
{
var query = (from s in entity.sales
join p in entity.products on s.Product_ID equals p.ProductID
where productId > 0 ? s.Product_ID == productId : s.Company_ID == companyId
select new { s, p }).ToList();
if (!string.IsNullOrEmpty(searchProduct))
{
query = query.FindAll(x => x.p.Description.ToLower().Contains(searchProduct.ToLower()));
}
// split s as List<sale> and p as List<product> to tuple output
return Tuple.Create(new List<sale>(), new List<product>() );
}
}
In the query result I see s and p, but how the exact them as a list with there properties in it so I can return them in Tuple.
Thanx Dinand
return Tuple.Create(query.Select(x => x.s).ToList(),
query.Select(x => x.p).ToList());

Self Join in Linq with null values c#

How can i get the rows that have null in the column used for self join ?
My code is :
IEnumerable<ListClassView> list = from l in lists join lp in lists on
l.ParentListId equals lp.Id
select new ListClassView()
{
Id = l.Id,
ListName = l.ListName,
Description = l.Description,
ParentName = lp.ListName,
IsActive = l.IsActive
};
I am unable to fetch rows where ParentListId=null. Is there a way where i can get all rows ?
Alternative syntax:
var list = lists.GroupJoin(
lists,
l => l.ParentListId,
lp => lp.Id,
(l, lp) => new ListClassView
{
Id = l.Id,
ListName = l.ListName,
Description = l.Description,
ParentName = lp.FirstOrDefault() == null ? null : lp.First().ListName,
IsActive = l.IsActive
});
I found the solution from here by applying a left join :
IEnumerable<ListClassView> list = from l in lists join lp in lists on
l.ParentListId equals lp.Id into lpp
from p in lpp.DefaultIfEmpty()
select new ListClassView()
{
Id = l.Id,
ListName = l.ListName,
Description = l.Description,
ParentName = p.ListName,
IsActive = l.IsActive
};
Now, It gets all rows including those with ParentListId = null

How to find same values in a list column and concatenating strings on the other rows for the same column value

I have a List with 2 columns with the following structure:
50 process:3333
50 phone:xxxx
51 process:2222
51 phone:yyyy
I need to build a new list based on that first one with this structure:
50 process:3333,phone:xxxx
51 process:2222,phone:yyyy
Does List have any method to find from one column a same value and concatenate the string on second column.
Or I have to find a way to do it manually using a foreach or a while statement?
Assuming a simple struct like...
public struct Proc
{
public int ID { get; set; }
public string Value { get; set; }
}
with your sample data:
var procList = new List<Proc>() {
new Proc{ID=50,Value="process:3333"},new Proc{ID=50,Value="phone:xxxx"},
new Proc{ID=51,Value="process:2222"},new Proc{ID=51,Value="phone:yyyy"},
};
You can use Enumerable.GroupBy and String.Join:
var procIdGroupList = procList
.GroupBy(p => p.ID)
.Select(g => new Proc
{
ID = g.Key,
Value = string.Join(",", g.Select(p => p.Value))
}).ToList();
DEMO
Found a workaround for that:
//Recupera valores dos indices para o tipo de documento
List<Gedi.Models.OperacoesModel.imports> valuesList = new List<Gedi.Models.OperacoesModel.imports>();
var valuesListObj = from a in context.sistema_Documentos
join b in context.sistema_Indexacao on a.id equals b.idDocumento
join c in context.sistema_Indexes on b.idIndice equals c.id
where a.ativo == 1
select new
{
id = a.id,
values = c.idName + ":" + b.valor
};
var çist = (from x in valuesListObj.AsEnumerable()
select new Gedi.Models.OperacoesModel.imports
{
id = x.id,
values = x.values
}).ToList();
var importList = çist.GroupBy(p => p.id).Select(g => new Gedi.Models.OperacoesModel.imports
{
id = g.Key,
values = string.Join(",", g.Select(p => p.values))
}).ToList();

Categories

Resources