Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Platform: C#
IDE: Visual Studio 2010
I am new to Linq and trying to filter a Json object using it. Any suggestions?
Here is the code:
string jsonGetData = objstats.getData_Emp(lblEmp.Text,lblYear.Text);
//JavaScriptSerializer strJsonSer = new JavaScriptSerializer();
var lstEmpAnalysis = JsonConvert.DeserializeObject<empAnalysis>(jsonGetData);
Now, from the above lstEmpAnalysis, I need to filter data on first table of the class empAnalysis where one of its index contains countries and show only those countries data being used in filter which is shown below :
public class empAnalysis
{
public List<List<object>> Table { get; set; }
public List<List<double>> Table1 { get; set; }
public List<List<object>> Table2 { get; set; }
}
So, any suggestions?
Input comes in this way :
Table
[0][0] : Abc
[0][1] : India
[0][2] : Engineer
[1][0] : Xyz
[1][1] : UK
[1][2] : Support Engineer
And what I want to filter is only the data which contains UK.
If you always know that second parameter of your table is the country you can do it like this :
var items= from item in empAnalysis.Table where item[1]=="UK" select item;
Although I always prefer to work with a strong typed object here as I mentioned in my comment :
For example :
public class Employee{
public string Name{get;set;}
public string Country{get;set;}
public string JobTitle{get;set;}
}
and
public class empAnalysis
{
public List<Employee> Table { get; set; }
public List<List<double>> Table1 { get; set; }
public List<List<object>> Table2 { get; set; }
}
then we could write :
var items= from employee in empAnalysis.Table where employee.Country=="UK" select item;
BTW for the purpose of clarity we can do something like this either :
var people=from item in empAnalysis.Table select new {
Title=item[0],
Country=item[1],
JobTitle=item[2],
};
var peopleFromUK=from person in people where person.Country=="UK";
Although you should be advised that you are getting a list of anonymous typed objects that have Title,Country and JobTitle properties.
UPDATE:
Here's a test that I wrote using NUnit and It passes.
[TestFixture]
public class LinqToObjectTests
{
[Test]
public void ThereShouldBeOnlyOneListForUK()
{
var list = new List<List<object>>
{
new List<object>(),
new List<object>()
};
list[0].Add("Name");
list[0].Add("UK");
list[0].Add("Title");
list[1].Add("Name");
list[1].Add("NOT UK");
list[1].Add("Title");
var query = from item in list where item[1] == "UK" select item;
Assert.AreEqual(1, query.Count());
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
i have a returned string looks like this
"{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}"
i have tries to Deserialize by using dictionary but still not catching the data.
the most important data is just named inside the properties, item1, item2
System.Text.Json.JsonSerializer.Deserialize<IDictionary<string, object>>(jsonString)
and it' giving the folowing result
[0] [KeyValuePair]:{[properties, {"Item1":{"dataType":"string"},"item2":{"dataType":"string"}
Key [string]:"properties"
Value [object]:ValueKind = Object : "{"item1":{"dataType":"string"},"item2":{"dataType":"string"}
Key [string]:"lastModified"
[1] [KeyValuePair]:{[lastModified, 2021-12-09T19:00:12Z]}
You can deserialize the JSON string to an object by following these simple steps:
Create a C# class from the JSON data. To do this, copy the JSON string and go to VS, Edit, Paste Special, Paste JSON as Classes.
if successful, you will get a C# class like this one
public class Rootobject
{
public Properties properties { get; set; }
public DateTime lastModified { get; set; }
}
public class Properties
{
public Item1 item1 { get; set; }
public Item2 item2 { get; set; }
}
public class Item1
{
public string dataType { get; set; }
}
public class Item2
{
public string dataType { get; set; }
}
You can rename the classes to anything that make meaning to you.
The you can deserialize like this
var obj = JsonConvert.DeserializeObject<Rootobject>(
"{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
Console.WriteLine(obj.properties.item2.dataType)// string
If you only need the value of dataType property and not the whole object, than you can use Linq to Json to get it without deserialization and object mapping.
The examples:
var obj = JObject.Parse("{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
var fistItemDataTypeValue = (string)obj["properties"]?["item1"]["dataType"];
var secondItemDataTypeValue = (string)obj["properties"]?["item2"]["dataType"];
Getting values as list of strings (NOTES: if you already know the number of items in json):
var obj = JObject.Parse("{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
var listOfValues = new List<string>();
for (int i = 1; i <= 2; i++)
{
listOfValues.Add((string)obj["properties"]?[$"item{i}"]["dataType"]);
}
! More about linq to json
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to get the vehicle type according to vehicle number. I need to select specific column from a list according to another column.
Here is my code:
protected void ddVehicleNo_SelectedIndexChanged(object sender, EventArgs e)
{
List<Exp_VehicleDTO> odata = (List<Exp_VehicleDTO>)Session["VehicleDTO"];
var vehityeps=odata.Select(x=>x.VehicleNo.Contains(x.VehicleType.Equals(Convert.ToInt32(ddVehicleNo.SelectedValue))))
}
This code causes error "the best overload method match for "string.contains(string)" has some invalid arguments".
Exp_vehicleDTO class
public class Exp_VehicleDTO
{
public int CompanyId { get; set; }
public int VehicleId { get; set; }
public int VehicleType { get; set; }
public string VehicleNo { get; set; }
public int Status { get; set; }
public DateTime CreatedDateTime { get; set; }
public string CreatedBy { get; set; }
public string CreatedMachine { get; set; }
}
You can get the vehicle type like so:
int vehicleType = odata.Single(x => x.VehicleNo.Equals(ddVehicleNo.SelectedValue)).VehicleType;
Single will take the first item that matches the condition. Note that it will throw an exception if the item isn't found, or if there are multiple matching items.
If you want to handle the case that the item isn't found, you can do something like this:
var vehicle = odata.SingleOrDefault(x => x.VehicleNo.Equals(ddVehicleNo.SelectedValue));
if (vehicle != null)
{
var vehicleType = vehicle.VehicleType;
}
else
{
// set combobox's SelectedIndex to -1
}
Difficult to help without knowing what error you are receiving but try changing your code to this:
protected void ddVehicleNo_SelectedIndexChanged(object sender, EventArgs e)
{
List<Exp_VehicleDTO> odata = (List<Exp_VehicleDTO>)Session["VehicleDTO"];
var vehityeps = odata
.Where(v => v.VehicleNo.ToString() == ddVehicleNo.SelectedValue)
.Select(v => v.VehicleType);
}
That should populate vehityeps with all VehicleType's where VehicleNo equals what the user has selected in the ddVehicleNo drop down.
UPDATED
I'm not sure what types are used Exp_VehicleDTO but my guess is VehicleNo is an int. To be safe with my solution this compares the values as strings.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a project coming up so I decided to look at the entity framework. If I don't have to create a data manager I think this would be the way to go, if it works. I see lots of things about it but none of them are clear.
It created this class
namespace EFTest
{
using System;
using System.Collections.Generic;
public partial class SalesRepresentative
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
}
}
How do I use it? Looking for examples I see things like this:
using (var ctx = new Context())
{
Employee emp = new Employee() { name = "Prashant" };
ctx.Employees.Add(emp);
ctx.SaveChanges();
}
I have a file called Model.Comntext with no context class in it. I tried changing it to dBContext but that doesn't work either.
I also found this:
CustomersComponent custc = new CustomersComponent();
Customers cust = custc.getCustomer(Id);
txtName.Text = cust.Name;
ddlCategories.SelectedValue = cust.Category.Id.ToString();
Well that has a Customer and a CustomerComponent. I have no such Component classes. I've spent half a day looking into this and am starting to wonder if the Entity Framework is a cousin of Microsoft Bob. Unless someone can tell me what I'm missing I will have to write my own data manager.
I resume step by step:
1 - Create a console project.
2 - Install EF using Nuget: Install-Package EntityFramework
3 - Create SalesRepresentative:
namespace EF {
public partial class SalesRepresentative {
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
}
}
4 - Create GeneralContext
namespace EF {
public class GeneralContext: DbContext {
public DbSet<SalesRepresentative> SalesRepresentatives { get; set; }
}
}
5 - So:
namespace EF {
class Program {
static void Main(string[] args) {
using (var ctx = new GeneralContext()) {
SalesRepresentative emp = new SalesRepresentative() { Name = "Prashant" };
ctx.SalesRepresentatives.Add(emp);
ctx.SaveChanges();
}
}
}
}
Note: In the App.config file (or web.config) you should customize the connection string.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I copied this code from this article and I don't get any idea why define class inside classes as properties. Also, what happens when the class PersonalLoan is instantiated ?
public class PersonalLoan
{
public string AccountNumber { get; set; }
public string AccounHolderName { get; set; }
public Loan LoanDetail { get; set; }
public PersonalLoan(string accountNumber)
{
this.AccountNumber = accountNumber;
this.AccounHolderName = "Sourav";
this.LoanDetail = new Loan(this.AccountNumber);
}
}
public class Loan
{
public string AccountNumber { get; set; }
public float LoanAmount { get; set; }
public bool IsLoanApproved { get; set; }
public Loan(string accountNumber)
{
Console.WriteLine("Loan loading started");
this.AccountNumber = accountNumber;
this.LoanAmount = 1000;
this.IsLoanApproved = true;
Console.WriteLine("Loan loading started");
}
}
I suspect that this code snippet is an example of what you should avoid: LoanDetail property of type Loan inside a class PersonalLoan suggests a has-a relationship between the classes. In other words, the authors of this code snippet are trying to say that
Personal loan has a Loan
This, however, is unlikely the relationship that they are trying to model: in reality,
Personal loan is a Loan
The relationship is-a is modeled using inheritance, not composition. In other words, they should have written this:
public class PersonalLoan : Loan {
public PersonalLoan(string accountNumber) : base(accountNumber) {
...
}
...
}
Another issue that points to the model being incorrect is that both PersonalLoan and the Loan inside it have the same accountNumber, which is stored in two places within the same object. When you see this, you know something is not right. The reason you get two account numbers is that when PersonalLoan gets instantiated, its constructor also instantiates Loan, passing it the same accountNumber.
This is not to say that embedding objects inside other objects is wrong. For example, if you were to model a borrower address as a class, you would end up with something like this:
class Address {
public string Country {get;set;}
public string City {get;set;}
... // And so on
}
class Borrower {
public Address MailingAddress {get;set;}
... //
}
This model is perfectly valid, because Borrower has an Address.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have three classes :
public class QData
{
public List<RData> Items { get; set; }
public List<QDay> Dates { get; set; }
}
public class QDay
{
public string Date { get; set; }
public List<RData> Details { get; set; }
}
public class RData
{
public string Name { get; set; }
public int Quantity { get; set; }
}
my list is
List<QData> myList;
What is the most effective way to sort the list (*QData type) by Date, the Date is string.
Perhaps this is what you need:
var result = myList.Select(qData => new QData()
{
Items = qData.Items,
Dates = qData.Dates.OrderBy(qDay => DateTime.Parse(qDay.Date)).ToList();
}).ToList();
With DateTime.Parse call being perhaps modified to fit to the date format in the qDay.Date property.
Here is an example that sort using the first date in the Dates list. I can't imagine why you would ever want to do this but here it is. I suspect that having Dates be a list is a mistake, in fact you only want one date there.
var sortedList = MyList.OrderBy(element => DateTime.Parse(element.Dates.First().Date));
I think this is what you actually want... ONLY ONE LIST:
public class QData
{
RData itemInfo { get; set;}
QDay dateInfo { get; set; }
}
Then your sort would look like this:
var sortedList = MyList.OrderBy(element => DateTime.Parse(element.dateInfo.Date));
var temp = (from e in myList.Dates
orderby DateTime.Parse(e.Date)
select e
).ToList();
myList.Dates = temp;