Group by multiple column into object and related lists - c#

After searching i couldn't link any answer found on this site to my issue
i have the following class
I have the following classes
public class Site
{
public string Name { get; set; }
public string Stauts { get; set; }
public string Demo { get; set; }
public List<Data> Datas { get; set; }
}
public class Data
{
public string IPT { get; set; }
public string Currency { get; set; }
public double Amount { get; set; }
}
I got data from external service in this format
"Name": "TcR",
"Stauts": "ACT",
"Demo": "BYD",
"IPT": "CATS",
"Currency": "EUR",
"Amount": "58.01",
"Name": "TcR",
"Stauts": "ACT",
"Demo": "BYD",
"IPT": "ROS",
"Currency": "USD",
"Amount": "25.01",
"Name": "TcR",
"Stauts": "ACT",
"Demo": "BYD",
"IPT": "SAP",
"Currency": "EUR",
"Amount": "44.01",
How can i transform this data to have one site and all related Data object in a list?
what i did
var result = from d in Loc
group d by new
{
Name = d.Name,
Stauts = d.Stauts,
Demo = d.Demo,
}
into g
select new Site
{
Name = g.Key.Name,
Stauts = g.Key.Stauts,
Demo = g.Key.Demo,
Datas = g.ToList()/// ==> error here
};

Assuimng you have that values in a list named _list, here's what you could do:
var grouped = _list
.GroupBy(item => new { item.Name, item.Status, item.Demo })
.Select(g => new Site()
{
Name = g.Key.Name,
Status = g.Key.Status,
Demo = g.Key.Demo,
Datas = g.Select(groupItem => new Data()
{
IPT = groupItem.IPT,
Currency = groupItem.Currency,
Amount = groupItem.Amount,
}).ToList(),
})
.ToArray();

Related

Return JSON response in array format in ASP.NET MVC 5 C#

I want to return JSON format from my database using asp.net mvc5 c#. I tried a lot of ways but was unable to generate data as per my requirement. I need the JSON array in this format.
{
"draw":0,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
[
"126",
"Test Name 1",
"07.01.2022 11:55 AM",
"Male"
],
[
"127",
"Test Name 2",
"01.02.2022 11:55 AM",
"Male"
]
]
}
Instead of this I am getting output in given format
{
"draw":0,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
{
"ID":126,
"Name":"Test Name 1",
"Date":"07.01.2022 11:55 AM",
"Gender":"Male"
},
{
"ID":127,
"Name":"Test Name 2",
"Date":"01.02.2022 11:55 AM",
"Gender":"Male"
}
]
}
My ASP.NET MVC5 C# code is below
public ContentResult GetDoctor()
{
var doctors = db.Doctors.Where(e => e.ID > 0);
var doct = doctors.Select(c => new
{
ID = c.ID + "," +
"," + c.Name +
"," + c.Date +
"," + c.Gender
}).ToList();
string students = string.Join("],[", doct.Select(e => e.ID.ToString()));
students = JsonConvert.SerializeObject(students);
JsonSerializerSettings hg = new JsonSerializerSettings();
hg.Formatting = Formatting.Indented;
hg.TypeNameHandling = TypeNameHandling.None;
string json = JsonConvert.SerializeObject(doctors.ToList(),hg);
return Content(json.ToString(), "application/json");
}
If you need to use strictly the first structure to return data, then the output structure must be:
public class Required_Result
{
[JsonProperty("draw")]
public int Draw { get; set; }
[JsonProperty("recordsTotal")]
public int RecordsTotal { get; set; }
[JsonProperty("recordsFiltered")]
public int RecordsFiltered { get; set; }
[JsonProperty("data")]
public List<List<string>> Data { get; set; }
}
Then I suposse the data you recover from database is in the second format:
public class Doctors_data
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Date")]
public string Date { get; set; }
[JsonProperty("Gender")]
public string Gender { get; set; }
}
public class Resume
{
[JsonProperty("draw")]
public int Draw { get; set; }
[JsonProperty("recordsTotal")]
public int RecordsTotal { get; set; }
[JsonProperty("recordsFiltered")]
public int RecordsFiltered { get; set; }
[JsonProperty("data")]
public List<Doctors_data> Data { get; set; }
}
So you need to transform your data into the required result format data and deserialize
Resume db = new Resume(); //<--- Populate your data
Required_Result result = new Required_Result()
{
Draw = db.Draw,
RecordsTotal = db.RecordsTotal,
RecordsFiltered = db.RecordsFiltered,
Data = db.Data.Where(e => e.ID > 0).Select(item => new List<string> { item.ID.ToString(), item.Name, item.Date, item.Gender }).ToList()
};
string result_string = JsonSerializer.Serialize(result);
You can use the following method:
return Json(new
{
draw = draw,
recordsFiltered = recordsTotal,
recordsTotal = recordsTotal,
data = doctors
});
Get draw values from UI. like this :
var draw = Request.Form.GetValues("draw").FirstOrDefault();
The doctors is your list.
The value of the record number is also obtained from the number of data in the list.
With this answer, you can send your data to the UI and load it into the datatable.
I use this standard in my projects and it works.

ChoETL nested JSON to CSV

I need to convert a json to csv. The problem is that I can't select everything that i need in the nested json structure. Example of the json file:
{
"system": {
"created": "2021-08-01T13:33:37.123Z",
"by": "web"
},
"location": {
"id": 100,
"country": "DE"
},
"order": [
{
"OrderID": 22,
"OrderName": "Soda",
"OrderArticles": [
{
"Size": 33,
"ProductName": "Coke",
"ProductId": "999"
},
{
"Size": 66,
"ProductName": "Fanta",
"ProductId": "888"
},
{
"Size": 50,
"ProductName": "Pepsi",
"ProductId": "444"
}
],
"ProcessedId": 1001,
"Date": "2021-08-02"
},
{
"OrderID": 23,
"OrderName": "Beverage",
"OrderArticles": [
{
"Size": 44,
"ProductName": "Coke",
"ProductId": "999"
}
],
"ProcessedId": 1002,
"Date": "2021-08-03"
}
]
}
This is the output i want:
created;by;id;country;OrderID;OrderName;Size;ProductName;ProductId
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;33;Coke;999
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;66;Fanta;888
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;50;Pepsi;444
2021-08-01T13:33:37.123Z;web;100;DE;23;Beverage;44;Coke;999
I can get the created and by values by them self and the values for OrderArticles. I just can't figure out how to get them togheter. This is the code I have used to get the result but divide into 2 different results:
using (var r = new ChoJSONReader(inBlob).WithJSONPath("$..order[*]").AllowComplexJSONPath(true))
{
return (r.SelectMany(r1 => ((dynamic[])r1.OutputArticles).Select(r2 => new
{
r1.OrderID,
r1.OrderName,
r1.Size,
r1.ProductName,
r1.ProductId
})));
}
using (var r = new ChoJSONReader(inBlob).WithJSONPath("$").AllowComplexJSONPath(true))
{
return (r.Select(r1 => new
{
r1.system.created,
r1.system.by
}));
}
Since you need system.created, system.by, location.id, location.country fields, you must load the entire json from root and then compose the expected object for the csv
Here are the working samples (Take the latest nuget packages)
METHOD 1: (Using dynamic model)
StringBuilder csv = new StringBuilder();
using (var r = new ChoJSONReader("*** YOUR JSON FILE PATH ***")
.JsonSerializationSettings(s => s.DateParseHandling = DateParseHandling.None)
)
{
using (var w = new ChoCSVWriter(csv)
.WithDelimiter(";")
.WithFirstLineHeader())
{
w.Write(r.SelectMany(root =>
((Array)root.order).Cast<dynamic>()
.SelectMany(order => ((Array)order.OrderArticles).Cast<dynamic>()
.Select(orderarticle => new
{
root.system.created,
root.system.by,
root.location.id,
order.OrderID,
order.OrderName,
orderarticle.Size,
orderarticle.ProductName,
orderarticle.ProductId,
})
)
)
);
}
}
Console.WriteLine(csv.ToString());
Output:
created;by;id;OrderID;OrderName;Size;ProductName;ProductId
2021-08-01T01:33:37.123Z;web;100;22;Soda;33;Coke;999
2021-08-01T01:33:37.123Z;web;100;22;Soda;66;Fanta;888
2021-08-01T01:33:37.123Z;web;100;22;Soda;50;Pepsi;444
2021-08-01T01:33:37.123Z;web;100;23;Beverage;44;Coke;999
METHOD 2: Using POCO model
Define POCO objects matching with input JSON
public class System
{
[JsonProperty("created")]
public string Created { get; set; }
[JsonProperty("by")]
public string By { get; set; }
}
public class Location
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
}
public class OrderArticle
{
[JsonProperty("Size")]
public int Size { get; set; }
[JsonProperty("ProductName")]
public string ProductName { get; set; }
[JsonProperty("ProductId")]
public string ProductId { get; set; }
}
public class Order
{
[JsonProperty("OrderID")]
public int OrderID { get; set; }
[JsonProperty("OrderName")]
public string OrderName { get; set; }
[JsonProperty("OrderArticles")]
public List<OrderArticle> OrderArticles { get; set; }
[JsonProperty("ProcessedId")]
public int ProcessedId { get; set; }
[JsonProperty("Date")]
public string Date { get; set; }
}
public class OrderRoot
{
[JsonProperty("system")]
public System System { get; set; }
[JsonProperty("location")]
public Location Location { get; set; }
[JsonProperty("order")]
public List<Order> Orders { get; set; }
}
Then use the code below to load the json and output CSV in expected format
StringBuilder csv = new StringBuilder();
using (var r = new ChoJSONReader<OrderRoot>("*** YOUR JSON FILE PATH ***")
.UseJsonSerialization()
)
{
using (var w = new ChoCSVWriter(csv)
.WithDelimiter(";")
.WithFirstLineHeader())
{
w.Write(r.SelectMany(root =>
root.Orders
.SelectMany(order => order.OrderArticles
.Select(orderarticle => new
{
created = root.System.Created,
by = root.System.By,
id = root.Location.Id,
order.OrderID,
order.OrderName,
orderarticle.Size,
orderarticle.ProductName,
orderarticle.ProductId,
})
)
)
);
}
}
Console.WriteLine(csv.ToString());
METHOD 3: Simplified dynamic model approach
StringBuilder csv = new StringBuilder();
using (var r = new ChoJSONReader("*** YOUR JSON FILE PATH ***")
.WithField("created", jsonPath: "$..system.created", isArray: false, valueConverter: o => ((DateTime)o).ToString("yyyy-MM-ddThh:mm:ss.fffZ"))
.WithField("by", jsonPath: "$..system.by", isArray: false)
.WithField("id", jsonPath: "$..location.id", isArray: false)
.WithField("country", jsonPath: "$..location.country", isArray: false)
.WithField("OrderID")
.WithField("OrderName")
.WithField("Size")
.WithField("ProductName")
.WithField("ProductId")
.Configure(c => c.FlattenNode = true)
)
{
using (var w = new ChoCSVWriter(csv)
.WithDelimiter(";")
.WithFirstLineHeader())
{
w.Write(r);
}
}
Console.WriteLine(csv.ToString());
METHOD 4: Even far simplified dynamic model approach
StringBuilder csv = new StringBuilder();
using (var r = new ChoJSONReader("*** YOUR JSON FILE PATH ***")
.Configure(c => c.FlattenNode = true)
.JsonSerializationSettings(s => s.DateParseHandling = DateParseHandling.None)
)
{
using (var w = new ChoCSVWriter(csv)
.WithDelimiter(";")
.WithFirstLineHeader()
.Configure(c => c.IgnoreDictionaryFieldPrefix = true)
)
{
w.Write(r);
}
}
Console.WriteLine(csv.ToString());
Sample fiddle: https://dotnetfiddle.net/VCezp8
Here is my solution.
This is my data model:
using System.Text.Json.Serialization;
namespace JsonToCSV.Models;
// Root myDeserializedClass = JsonSerializer.Deserialize<Root>(myJsonResponse);
public class System
{
[JsonPropertyName("created")]
public string Created { get; set; }
[JsonPropertyName("by")]
public string By { get; set; }
}
public class Location
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("country")]
public string Country { get; set; }
}
public class OrderArticle
{
[JsonPropertyName("Size")]
public int Size { get; set; }
[JsonPropertyName("ProductName")]
public string ProductName { get; set; }
[JsonPropertyName("ProductId")]
public string ProductId { get; set; }
}
public class Order
{
[JsonPropertyName("OrderID")]
public int OrderID { get; set; }
[JsonPropertyName("OrderName")]
public string OrderName { get; set; }
[JsonPropertyName("OrderArticles")]
public List<OrderArticle> OrderArticles { get; set; }
[JsonPropertyName("ProcessedId")]
public int ProcessedId { get; set; }
[JsonPropertyName("Date")]
public string Date { get; set; }
}
public class Root
{
[JsonPropertyName("system")]
public System System { get; set; }
[JsonPropertyName("location")]
public Location Location { get; set; }
[JsonPropertyName("order")]
public List<Order> Orders { get; set; }
}
and here is business logic (if you want, I can replace it with LINQ):
using System.Text.Json;
using JsonToCSV.Models;
var dataAsText = File.ReadAllText("data.json");
var data = JsonSerializer.Deserialize<Root>(dataAsText);
var csv = new List<string> { "created;by;id;country;OrderID;OrderName;Size;ProductName;ProductId" };
foreach (var order in data.Orders)
{
foreach (var orderArticle in order.OrderArticles)
{
csv.Add(String.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8}",
data.System.Created,
data.System.By,
data.Location.Id,
data.Location.Country,
order.OrderID,
order.OrderName,
orderArticle.Size,
orderArticle.ProductName,
orderArticle.ProductId
));
}
}
File.WriteAllLines("data.csv", csv);
Creates .csv file with content:
created;by;id;country;OrderID;OrderName;Size;ProductName;ProductId
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;33;Coke;999
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;66;Fanta;888
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;50;Pepsi;444
2021-08-01T13:33:37.123Z;web;100;DE;23;Beverage;44;Coke;999

How to groupby list in c# and show result without foreach?

I am using .net core 5 web api project. I have following classes:
public class GroupedShowbackSummaryListDto
{
public int RuleId { get; set; }
public string RuleName { get; set; }
public decimal TotalPrice { get; set; }
public List<GroupedProjectForShowbackSummary> Projects { get; set; }
}
public class GroupedProjectForShowbackSummary
{
public int? Id { get; set; }
public string Name { get; set; }
public decimal TotalPrice { get; set; }
}
I would like group by rule id and show list of projects as response, I am trying:
var queryable = _context.ShowbackSummaries.Where(x => x.ProjectId != null).AsQueryable();
var summary = queryable.ToList();
var grouped = summary.GroupBy(x => x.ShowbackRuleId).Select(c => new GroupedShowbackSummaryListDto
{
RuleId = c.Key,
RuleName = c.Select(f => f.ShowbackRule.Name).First(),
TotalPrice = c.Select(f => f.Price).Sum(),
Projects = new List<GroupedProjectForShowbackSummary>
{
new()
{
Id = c.Select(f => f.ProjectId).First(),
Name = c.Select(f => f.Project.Name).First(),
TotalPrice = c.Select(f => f.Price).First()
}
}
}).ToList();
return grouped;
I know I am using first and it returns only first project but I would like to return all, if I switch to list int id for ex, it will show me:
[
100,
101,
...
]
I would like multiple result for my current response:
[
{
"ruleId": 1,
"ruleName": "rule-1",
"totalPrice": 400,
"projects": [
{
"id": 1169,
"name": "lubos-cncf",
"totalPrice": 200
}
]
},
{
"ruleId": 2,
"ruleName": "rule-2",
"totalPrice": 300,
"projects": [
{
"id": 1169,
"name": "lubos-cncf",
"totalPrice": 300
}
]
}
]
P.S. Get all projects like this.
This should work (inside your GroupBy-Expression):
Projects = c.Select(f =>
new GroupedProjectForShowbackSummary()
{
Id = f.ProjectId,
Name = f.Project.Name,
TotalPrice = f.Price
}).ToList()

Mongodb C# Update element in an multiple array with multiple values

I want to update the single document in collection with the guid as filter and update value is cityType. Every guid has different citytype here i have used 3 types it may be more.
So please give a right implementation using c# code.
Models:
public class Country
{
[BsonId]
public ObjectId Id { get; set; }
public int CountryId {get; set; }
public IEnumerable<States> States { get; set; }
}
public class States
{
public Guid Guid { get; set; }
public CityType CityType { get; set; }
}
Enum CityType
{
Unknown = 0,
Rural = 1,
Urban = 2
}
Existing Collection:
{
"_id": ObjectId("6903ea4d2df0c5659334e763"),
"CountryId": 200,
"States": [
{
"Guid": "AFCC4BE7-7585-5E46-A639-52F0537895D8",
"CityType": 0,
},
{
"Guid": "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
"CityType": 0,
}
}
Input:
List<States>()
{
new States()
{
Guid = "AFCC4BE7-7585-5E46-A639-52F0537895D8",
CityType = CityType.Rural
},
new States()
{
Guid = "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
CityType = CityType.Urban
}
}
Expected:
{
"_id": ObjectId("6903ea4d2df0c5659334e763"),
"CountryId": 200,
"States": [
{
"Guid": "AFCC4BE7-7585-5E46-A639-52F0537895D8",
"CityType": 1,
},
{
"Guid": "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
"CityType": 2,
}
}
This is the method I have tried:
public async Task<bool> UpdateType(int countryId, IEnumerable<States> states)
{
var collection = connectionFactory.GetCollection<Country>(collectionName);
var cityTypes = states.Select(x => x.CityType);
var filter = Builders<Country>.Filter.Empty;
var update = Builders<Country>.Update.Set("States.$[edit].CityType", cityTypes);
var arrayFilters = new List<ArrayFilterDefinition>();
foreach (var state in states)
{
ArrayFilterDefinition<Country> optionsFilter = new BsonDocument("state.Guid", new BsonDocument("$eq", state.Guid));
arrayFilters.Add(optionsFilter);
}
var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
var result = await collection.UpdateOneAsync(filter, update, updateOptions);
return result;
}
hope all details I have added here. Thanks in advance.
You don't have to loop through it:
Let's say you have a Class1 like this:
class Question : AuditableEntity {
public string Text { get; set; }
public List<string> Tags { get; set; } = new List<string>();
so you just say:
await collection.UpdateOneAsync(
someFilter,
Builders<Class1>.Update
.Set(f => f.Text, request.Question.Text)
.Set(f => f.Tags, request.Question.Tags));

How to create json structure from list of data?

I want to create json structure with nested object from my list object.
This is my class:
public class Employee
{
public int EmployeeId { get; set; }
public int Skillssetpoints { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
public class EmployeeModel
{
public int EmployeeId { get; set; }
public List<int> Skillssetpoints { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
Records are like this:
EmployeeId SkillssetPoints Date
1 10 4/5/2016 16:12:12
2 12 3/5/2016 17:12:12
3 4 8/5/2016 8:12:12
4 20 1/5/2016 2:12:12
This is how i am getting data:
var data=context.Employee.Tolist();
After getting data i want to create this json structure from above data using EmployeeModel and return:
Expected Output:
{"Date":"8-5-2016 08:12:12","SkillssetPoints":[4,10,12,20]}
In Date field i would take Highest date so 8-5-2016 and SkillssetPoints will be order by ascending.
How to create this json structure with my EmployeeModel class??
Add a reference to the nuget package Newtonsoft.Json then use ...
string result = JsonConvert.Serialize(data);
It looks like you need to translate the data in your db to the model format by doing a projection first then serialize the result ...
var groupedData = data
.GroupBy(s => s.EmployeeId)
.OrderBy(s => s.Date)
.Select(g => new EmployeeModel {
EmployeeId = g.Key,
Name = g.First().Name,
Date = g.First().Date,
Skillssetpoints = g.Select(s => s.Skillssetpoints).OrderBy(i => i).ToList()
});
That should produce a collection of this model ...
public class EmployeeModel
{
public int EmployeeId { get; set; }
public List<int> Skillssetpoints { get; set; }
public string Name { get; set; }
public DateTime? Date { get; set; }
}
... when I do this ...
var data = new List<EmployeeModel> {
new EmployeeModel { EmployeeId = 1, Name = "Homer Simpson", Skillssetpoints = new List<int> { 1,2,3,4 }, Date = DateTime.Now },
new EmployeeModel { EmployeeId = 2, Name = "Marge Simpson", Skillssetpoints = new List<int> { 1,2,3,4 }, Date = DateTime.Now },
new EmployeeModel { EmployeeId = 3, Name = "Lisa Simpson", Skillssetpoints = new List<int> { 1,2,3,4 }, Date = DateTime.Now },
new EmployeeModel { EmployeeId = 4, Name = "Bart Simpson", Skillssetpoints = new List<int> { 1,2,3,4 }, Date = DateTime.Now }
};
var result = JsonConvert.SerializeObject(data);
I get this output ...
[
{
"EmployeeId": 1,
"Skillssetpoints": [1,2,3,4],
"Name": "Homer Simpson",
"Date": "2016-04-05T11:42:09.9126748+01:00"
},
{
"EmployeeId": 2,
"Skillssetpoints": [1,2,3,4],
"Name": "Marge Simpson",
"Date": "2016-04-05T11:42:09.9126748+01:00"
},
{
"EmployeeId": 3,
"Skillssetpoints": [1,2,3,4],
"Name": "Lisa Simpson",
"Date": "2016-04-05T11:42:09.9126748+01:00"
},
{
"EmployeeId": 4,
"Skillssetpoints": [1,2,3,4],
"Name": "Bart Simpson",
"Date": "2016-04-05T11:42:09.9126748+01:00"
}
]
Use newton JSON,it is available on NuGet and code is extremely easy.
using Newtonsoft.Json;
var jsonList = JsonConvert.SerializeObject(context.Employee.Tolist());
Cheers
Select your required records by grouping on particular field and then prepare the anonymous object in required pattern and serialize it for final results,
var models = (from em in employeeModels
group em by em.ID into g
select new
{
Id = g.Key,
maxDate = g.Max(p => p.Date)
}).ToList();
var result = new
{
date = prices.Max(p => p.maxDate),
SkillssetPoints = prices.Select(p => p.Id).ToList()
};
var json = JsonConvert.SerializeObject(result);
You will get the json in the pattern like
{
"date": "2016-04-05T16:39:54.8420979+05:30",
"SkillssetPoints": [
1,
2,
3
]
}
Use Newton JSON from Nuget Package and try This code
List lstEmp = new List();
for (int i = 1; i <= 4; i++)
{
Employee emp = new Employee();
emp.EmployeeId = i;
emp.Name = "Name" + i;
emp.Skillssetpoints = i + 1;
emp.Date = DateTime.Now.AddDays(i);
lstEmp.Add(emp);
}
var data = lstEmp;
var result = new EmployeeModel
{
Date = data.Max(p => p.Date),
Skillssetpoints = data.Select(p => p.Skillssetpoints).ToList()
};
var JsonData = JsonConvert.SerializeObject(new
{
Date = result.Date,
Skillssetpoints = result.Skillssetpoints
});
Cheers
1) Install Newtonsoft.Json package using NuGet
2) add namespace on top
using Newtonsoft.Json;
3) Add [JsonIgnore] on top of Model class properties which you don't want to include in json conversion
public class Employee
{
public int EmployeeId { get; set; }
public int Skillssetpoints { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
public class EmployeeModel
{
[JsonIgnore]
public int EmployeeId { get; set; }
public List<int> Skillssetpoints { get; set; }
[JsonIgnore]
public string Name { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
4) Final code is below
var data = new List<Employee>();
data.Add(new Employee { EmployeeId = 1, Skillssetpoints = 10, Date = Convert.ToDateTime("4/5/2016 16:12:12") });
data.Add(new Employee { EmployeeId = 2, Skillssetpoints = 12, Date = Convert.ToDateTime("3/5/2016 17:12:12") });
data.Add(new Employee { EmployeeId = 3, Skillssetpoints = 4, Date = Convert.ToDateTime("8/5/2016 8:12:12") });
data.Add(new Employee { EmployeeId = 4, Skillssetpoints = 20, Date = Convert.ToDateTime("1/5/2016 2:12:12") });
var highestDate = data.OrderByDescending(e => e.Date).First().Date;
var skillssetpointsList = data.Select(e => e.Skillssetpoints).ToList();
EmployeeModel employeeModel = new EmployeeModel()
{
Date = highestDate,
Skillssetpoints = skillssetpointsList
};
string jsonString = JsonConvert.SerializeObject(employeeModel);
Now, jsonString = {"Skillssetpoints":[10,12,4,20],"Date":"2016-05-08T08:12:12"}
You may try to create a new object and serialize as below:
var result = JsonConvert.Serialize (new {
Date = context.Employee.Max(e => e.Date),
SkillssetPoints = context.Employee.Select(e => e.SkillssetPoints)
}));
i think you can try this
it works fine with me.
public ActionResult GetCitiesWithBranches(int regionID)
{
var cities =
_context.Cities.Where(e => e.RegionCode == regionID)
.Select(e => new { ID = e.CityCode, Name = e.Name })
.ToList();
return Json(new { cities = cities });
}
and in the view i am using that:
var json = { regionID: data };
$.ajax({
type: "POST",
url: '#Url.Action("GetCitiesWithBranches", "Admin")',
data: json,
dataType: "json",
error: function (xhr, status, error) {
//alert("error routine");
},
success: function (res) {
if (res.cities) {
}
}
});
Hope that will help..

Categories

Resources