C# Nullable List [closed] - c#

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 last month.
Improve this question
Are all the following valid ? They are properties of a class instantiated to _s.
public List<int>? _Int1 { get; set; }
public List<int?> _Int2 { get; set; }
public List<Nullable<int>> _Int3 { get; set; }
I've tried all of them and it all work. However, when I assign the value, it has to match the exact way it was defined, ie:
_s._Int1 = new List<int> { 0 } ;
_s._Int2 = new List<int?> { 0 };
_s._Int3 = new List<Nullable<int>> { 0 };
If I were to assign differently, then I get the following:
_s._Int1 = new List<int?> { 0 } ; // fail
_s._Int2 = new List<Nullable<int>> { 0 }; // OK
_s._Int3 = new List<int?> { 0 }; // OK
My questions is what is the correct way to declare a Nullable. Thanks.

Please, note that T? can mean two different things:
If T is struct, then T? is Nullable<T>
If T is class then T? means nullable reference type, it means that the instance is not supposed to be null
PLease, see https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references for details
In your question int? is a case #1, since int is a struct, when List<int?> is a case #2, since List<T> is a class:
// _Int1 is List<int>
// _Int1 can be null
public List<int>? _Int1 { get; set; }
// _Int2 is List<Nullable<int>>
// _Int2 is not supposed to be null
public List<int?> _Int2 { get; set; }
// Longer version of _Int2 type declaration
// _Int3 is List<Nullable<int>>
// _Int3 is not supposed to be null
public List<Nullable<int>> _Int3 { get; set; }

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; }
}

Parse nested values in C# dictionary [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 C# application has the below json which is deserialized to a dictionary which is assigned to values:
{
"armSpan": 1.8081974983215332,
"handPosition": {
"x": 1.23,
"y": 1.74,
"z": 2.05,
}
}
This is the code which deserializes:
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
I want to assign data from it to various fields in my Size model. For armSpan I'm happy that the following works:
size.ArmSpan = decimal.Parse(values["armSpan"]);
I'm not sure how to get the values of x, y and z though. should it be something like
size.HandPosX = decimal.Parse(values["handPosition"]["x"]);
or
size.HandPosX = decimal.Parse(values["handPosition"].["x"]);
There are online converters to generate c# code based on your json (search for "JSON to C#"). With one of those, I made these classes based on the json you supplied (removed the extra comma in '"z": 2.05,'):
public partial class ClassYouDeserializeTo
{
[JsonProperty("armSpan")]
public double ArmSpan { get; set; }
[JsonProperty("handPosition")]
public HandPosition HandPosition { get; set; }
}
public partial class HandPosition
{
[JsonProperty("x")]
public double X { get; set; }
[JsonProperty("y")]
public double Y { get; set; }
[JsonProperty("z")]
public double Z { get; set; }
}
You can use them like this:
var values = JsonConvert.DeserializeObject<ClassYouDeserializeTo>(response);

How to count, sum, etc. an IList or List [closed]

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 2 years ago.
Improve this question
I'm pretty new to C#. A simplified version of my current problem is:
I have a range of fruit (criteria) and on any given day the change values will be between -1.5 and 2 including 0, or no value (null). This will change from day to day.
Fruit Change
Apple 1.5
Banana
Grape 0
Lemon -1
Melon
Pear 2
From that data I need to be able to determine 3 values (from those I can then calculate others):
Sum the available values for Change
Count the fruit that have Change data (excluding nulls)
Count the total number of Fruit available (with and without data)
To future proof this, I assume an IList would allow me to one day simply add/remove fruit with a change value and then the above formulas will keep working
I assume I'll need:
public string Fruit { get; set; }
public decimal? Change { get; set; }
public decimal? SumChange { get; set; }
public int CountChange { get; set; }
public int CountFruit { get; set; }
My questions are:
Which will solve my problem better, a List or an IList and how do I declare/initiate it?
For that List/IList, how do I set the Change value for a specific Fruit including the Nulls?
What code do I need to get the 3 values I'm after from the List/IList?
Thanks
You need to use System.Linq, System.Collections.Generic
Here's what you need:
// Important:
using System.Collections.Generic;
using System.Linq;
static void Main()
{
List<Fruit> fruits = new List<Fruit>()
{
new Fruit() { Name = "Apple", Change = 1.5m },
new Fruit() { Name = "Banana", Change = null },
new Fruit() { Name = "Grape", Change = 0m },
new Fruit() { Name = "Lemon", Change = -1m },
new Fruit() { Name = "Melon", Change = null },
new Fruit() { Name = "Pear", Change = 2m },
};
decimal? sum_of_changes = fruits.Sum(f => f.Change);
int fruit_with_change_data = fruits.Count(f => f.Change != null);
int count_of_all_fruit = fruits.Count();
}
public class Fruit
{
public string Name { get; set; }
public decimal? Change { get; set; }
}

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.

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