LINQ groupby and json output [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
my task is to group the data from a list of Subscription object which has the following structure:
public class Subscription
{
public string ApplicationId { get; private set; }
public string UserCode { get; private set; }
public string SubscriptionId { get; private set; }
public string SubscriptionCode { get; private set; }
public DateTime? StartDate { get; private set; }
public DateTime? EndDate { get; private set; }
}
The code return a list of subscription, so List. In my case I've several items with same ApplicationId but different StartDate and EndDate. Basically I have to group these items
in order to create a json structure like this:
"applicationId" : {
"subscriptions" : [
{
"startdate" : ...,
"enddate" : ...,
},
{
"startdate" : ...,
"enddate" : ...,
},
]
}
Can I achieve this using LINQ?

Try this:
subscriptions.GroupBy(item => item.SubscriptionCode)
.Select(group => new { Subscription = group.Key, Items = group.Select(item => new { StartDate = item.StartDate, EndDate = item.EndDate}) })
Not sure if it will work but it reads like it will.
subscriptions is just a list of your object.

Related

Create Dictionary with custom class for value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
I'm using a dictionary in C# and want to make the value a custom class. I have the following code.
public class myMovies
{
public string Name { get; set; }
public string Year { get; set; }
}
Dictionary<string, myMovies> file_dict = new Dictionary<string, myMovies>();
foreach (string file in Directory.GetFiles(path1, "*.mkv", SearchOption.AllDirectories))
{
file_dict.Add(file, new myMovies("x", "x");
}
I'm doing something wrong, I just have no idea at this point. As a side note, this code does work when I just use a <string,string> dictionary and just store a text value in the value pair.
Edit
Required a constructor in my class definition. Thanks for help.
Either provide an appropriate constructor in the class definition:
public class myMovies
{
public string Name { get; set; }
public string Year { get; set; }
public myMovies(string name, string year)
{
Name = name;
Year = year;
}
}
Or use object initializer syntax to assign the property values when instantiating the object:
file_dict.Add(file, new myMovies { Name = "x", Year = "x" });
It's telling you it expects a Constructor, so give it what it expects:
public class myMovies
{
public myMovies(string name, string year)
{
Name = name;
Year = year;
}
public string Name { get; set; }
public string Year { get; set; }
}

How to parse complex json to c# .net classes [closed]

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
my json is as given below. i need to convert it into c# class. Please note all values will be different in actual scenario.
{
'aa-AA': {
lanCODE: 'aa-AA',
genNames: {
female: ['Wavenet'],
male: ['Bavenet', 'Bavenet'],
},
default: 'Wavenet',
systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
name: 'xxxx',
},
'aa-AA': {
lanCODE: 'aa-AA',
genNames: {
female: ['Wavenet'],
male: ['Bavenet', 'Bavenet'],
},
default: 'Wavenet',
systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
name: 'xxxx',
},
'aa-AA': {
lanCODE: 'aa-AA',
genNames: {
female: ['Wavenet'],
male: ['Bavenet', 'Bavenet'],
},
default: 'Wavenet',
systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
name: 'xxxx',
}
}
The initial property is almost certainly meant to be a dictionary key, so I would go with something like this:
public class Language
{
[JsonProperty("lanCODE")]
public string LanguageCode { get; set; }
public string Default { get; set; }
public List<string> SystemLocale { get; set; }
public GenNames GenNames { get; set; }
}
public class GenNames
{
public List<string> Female { get; set; }
public List<string> Male { get; set; }
}
And deserialise like this:
var languages = JsonConvert.DeserializeObject<Dictionary<string, Language>>(json);

select from list using LINQ's Where [closed]

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.

Trying to load an XML into a class object using XElement and LINQ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have the following XML
<Workflow Name="Workflow1">
<Parameter Name="Parameter1">Value1</Parameter>
<Parameter Name="Parameter2">Value2</Parameter>
<Environment Name="Environment1" Type="Typ1">
<DataCenter Name="DC1" DeployEnvironmentName="blah"/>
</Environment>
<Environment Name="Environment2" Type="Typ2">
<DataCenter Name="DC2" DeployEnvironmentName="blah"/>
</Environment>
I am trying to read this XML into the following objects
class Workflow
{
public string Name { get; set; }
public IEnumerable<Parameter> Parameters { get; set; }
public IEnumerable<Environment> Environments { get; set; }
}
class Environment
{
public string Name { get; set; }
public EnvironmentType Type { get; set; }
public IEnumerable<DataCenter> DataCenters { get; set; }
}
class Parameter
{
public string Name { get; set; }
public string Value { get; set; }
}
class DataCenter
{
public string Name { get; set; }
public string DeployEnvironmentName { get; set; }
}
using the following expression
var root = XElement.Load(filePath);
var workflows =
root.Elements("Workflow")
.Select(
e =>
new Workflow
{
Name = e.Attribute("Name").Value,
Parameters = e.Elements("Parameter")
.Select(p =>
new Parameter { Name = p.Attribute("Name").Value, Value = p.Value }),
Environments = e.Elements("Environment").Select(
p =>
new Environment
{
Name = p.Attribute("Name").Value,
Type = (EnvironmentType)Enum.Parse(typeof
(EnvironmentType), p.Attribute("Type").Value, true),
DataCenters = p.Elements("DataCenter").Select(
dc => new DataCenter {
Name = dc.Attribute("Name").Value, DeployEnvironmentName = dc.Attribute
("DeployEnvironmentName").Value })
});
});
I keep getting a syntax error. For some reason, it doesn't seem to like these nested expressions. Anyone know what could be going wrong or know of a better way to do this? Thanks in advance
you need to remove this semicolon
Name = p.Attribute("Name").Value,
Type = (EnvironmentType)Enum.Parse(typeof
(EnvironmentType), p.Attribute("Type").Value, true),
DataCenters = p.Elements("DataCenter").Select(
dc => new DataCenter {
Name = dc.Attribute("Name").Value, DeployEnvironmentName = dc.Attribute
("DeployEnvironmentName").Value })
});
^^^
});
You shouldn't use semicolons in object initializers, you should separate the properties with comma.
Your XML file seems to be broken. The Workflowtag was never closed.

Order list where date is string [closed]

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;

Categories