unable to get list of elements in list - c#

i have 2 model classes
public class ProductOptionRequest
{
public string Name { set; get; }
public List<ProductValuesRequest> productValues { get; set; }
}
public class ProductValuesRequest
{
public string ValueName { get; set; }
}
public class ProductOptionValue
{
public int OptionId { get; set; }
public String ValueName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
and wrote one bs method and passing parameter value as value names. but I'm unable to get those values in a list object as productValues. May I know the solution, please.
public async Task<ReturnString> SaveProductOption(ProductOptionRequest request)
{
request.productValues = new List<ProductValuesRequest>();
foreach (ProductValuesRequest valueRequest in request.productValues)
{
ProductOptionValue res = new ProductOptionValue();
res.ValueName = valueRequest.ValueName;
object response = await productOptionValueRepository.InsertAsync(res, true);
}
}

In the first line of your method, you are replacing the productValues property of request object with a new empty list, :
request.productValues = new List<ProductValuesRequest>();
Therefore, in foreach loop, you are iterating on an empty list.
Remove the first line and see if you still have any issues.

You are assigning an emplty list to productValues as
request.productValues = new List() and trying to iterate the empty list.

Related

Merge two identical object model class after JsonConvert.DeserializeObject

C# and Newtonsoft.JSON
I've an object model class like this
class RolePerson
{
public NodeRolePerson[] Items { get; set; }
}
class NodeRolePerson
{
public bool active { get; set; }
public string dateUva { get; set; }
public bool delegated { get; set; }
public NodeentityOrg entityOrg { get; set; }
.....
public string userUva { get; set; }
}
.........
Now i get data with
RolePerson myP1 = JsonConvert.DeserializeObject<RolePerson>(data1,settings);
RolePerson myP2 = JsonConvert.DeserializeObject<RolePerson>(data2,settings);
How can i have only one object with both myP1 and myP2 ?
I've tried with
List<RolePerson> trace;
trace.Add(myP1);
trace.Add(myP2);
but receive a compilation error 'local variable not assigned'.
Thanks so much.
You never actually created a new list:
List<RolePerson> trace = new List<RolePerson>();
trace.Add(myP1);
trace.Add(myP2);
try this
var items = new List<NodeRolePerson>(myP1.Items);
items.AddRange(myP2.Items);
RolePerson trace = new RolePerson { Items = items.ToArray() };

How do I send a Object Linq sorted List as a parameter

I am trying to make my code more compromised, and use overall less, however currently I'm running into the problem of not being able to send a list of Objects sorted by linq as a parameter.
the problem is in this part of the code:
List<Afspraken> dataAfspraken = new List<Afspraken>();
public Form1()
{
InitializeComponent();
fillListsForLinq();
loadReceptionData();
}
private void fillListsForLinq()
{
dataAfspraken = data.getAfsprakenData();
//here it fills the list with Afspraken objects
}
private void loadReceptionData()
{
private void loadReceptionGrid
var receptionToFinnish =
(from AFspraken in dataAfspraken
where Afspraken.factuur_betaald == true && Afspraken.volledig_afgerond == false
join Users in dataUsers on Afspraken.gekoppelde_klant equals Users.id
select new
{
Id = Afspraken.id,
Klant = Users.gebruikersnaam,
Betaald = Afspraken.factuur_betaald,
Afgerond = Afspraken.volledig_afgerond
}).ToList();
changeDataviewReception(receptionToFinnish);
}
private void changeDataviewReception(List<Object> listData)
{
dgvReceptionData.DataSource = listData
}
the Afspraken class looks like this
public class Afspraken
{
public int id { get; set; }
public bool bevestigd { get; set; }
public DateTime datum { get; set; }
public int gekoppelde_klant { get; set; }
public int gekoppelde_monteur { get; set; }
public string benodigde_hadelingen { get; set; }
public decimal totaalprijs { get; set; }
public bool klaar { get; set; }
public bool factuur_betaald { get; set; }
public bool volledig_afgerond { get; set; }
public string opmerkingen { get; set; }
}
How do I get receptionToFinnish as a parameter into changeDataviewReception?
receptionToFinnish will be a list full of objects of an anonymous type. But your method requires a List<object>. This is now allowed since a list is not a variant type.
Say for example that you have a list of bananas and want to give it to someone that wants a list of fruits. This will not work since that other person might try to add an orange to the list of bananas.
To fix this, cast the values to object explicitly, for example:
select new
{
Id = Afspraken.id,
Klant = Users.gebruikersnaam,
Betaald = Afspraken.factuur_betaald,
Afgerond = Afspraken.volledig_afgerond
} as object

cast a response object type to a list C#

i am hitting a webservice which is returning me a object Items in which i have a collection airpricepoint. I have created similar classes items and airpricepoint i am trying to cast the lowFareSearchRsp.Items to IList collection so that i can foreach loop and access the inner collections but i am unable to loop through i cant access the collection inside of fareitems
IList collection = (IList)lowFareSearchRsp.Items;
if (collection != null)
{
foreach (var fareitems in collection)
{
items itemsobj = new items();
Document.airpricepoint airpricepointobj = new airpricepoint();
airpricepointobj.AirPricingInfo = new List<airpricinginfo>();
airpricepointobj.AirPricingResultMessage = fareitems.AirPricingResultMessage;
airpricepointobj.FeeInfo = fareitems.FeeInfo;
airpricepointobj.FareNote = fareitems.FareNote;
airpricepointobj.TaxInfo = fareitems.TaxInfo;
airpricepointobj.Key = fareitems.Key;
airpricepointobj.TotalPrice = fareitems.TotalPrice;
airpricepointobj.BasePrice = fareitems.BasePrice;
}
public class items
{
public IList<airpricepoint> AirPricePoint { get; set; }
}
public class airpricepoint
{
public IList<airpricinginfo> AirPricingInfo { get; set; }
public object AirPricingResultMessage { get; set; }
public object FeeInfo { get; set; }
public object FareNote { get; set; }
public object TaxInfo { get; set; }
public string Key { get; set; }
public string TotalPrice { get; set; }
public string BasePrice { get; set; }
}
If it's indeed a web service, then you already know the structure (format) of the data you're receiving. Usually it will be in JSON or XML format; or packaged in a contract class if it's a WCF service.
This means that you can simply de-serialize the data using any JSON or XML serialization library.

C# - Using a model that contains a model of arrays

I have this model that I am trying to reference and get the an array of this type.
public class TestModel
{
public string Name { get; set; }
public Guid Id { get; set; }
public List<Conditions> Conditions { get; set; }
}
I also need to get the conditions for this which is a separate model with a few arrays.
public class Conditions
{
public List<string> Country { get; set; }
public List<int> Grades { get; set; }
public List<string> Disciplines { get; set; }
}
I can get the Name and Id easily enough but when I try and get the values in any of the arrays I get an error Object reference not set to an instance of an object. which it would normally give as the array is not instantiated. Is there any way to do this without instantiating the array?
Code I am using to get the Id
private static ArrayList GetTests()
{
Console.WriteLine("Get tests");
foreach (TestModel test in testModel)
{
var conditions = test.Conditions.Disciplines;
Console.WriteLine("");
Console.WriteLine("testID: " + test.Id);
}
return networks;
}
The model is populated in the main method:
private static IEnumerable<TestModel> testModel= new TestModel[] { };
public static void Main(string[] args)
{
Console.WriteLine("Start");
Console.WriteLine("Load Test Data");
using (var r = new StreamReader(#"C:\Production\test.json"))
{
string json = r.ReadToEnd();
testModel = JsonConvert.DeserializeObject<TestModel[]>(json);
}
GetTests();
Console.WriteLine("End");
Console.Read();
}
I feel like this should be populated when the Json file is read and put into the model.
As you said: You did not instantiate the arrays.
You could for example do it in the constructor, use the setters or simply do it inline (C# 6.0 required):
public class Conditions
{
public string[] Country { get; set; } = new string[length];
public int[] Grades { get; set; } = new int[length];
public string[] Disciplines { get; set; } = new string[length];
}
"length" is the length of the array. If you don't know the size, you might consider using a List<> or something like that.
Switching to List for each of the properties worked. I shall edit the code above with the correct answer, Thanks to #Thomas D. for pointing me in that direction

C# Copy List items to Object Arrays

I have a list created from a stored procedure using EF6.0
I have also created 3 classes
public class Resas
{
public string todo{ get; set; }
public string prop { get; set; }
public string Code { get; set; }
public string statusCode { get; set; }
public string checkin { get; set; }
public string checkout { get; set; }
public List<profiles> profiles { get; set; }
}
public class profiles
{
public string action { get; set; }
public string id { get; set; }
public string profileType { get; set; }
public string title { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public List<emailAddresses> emailAdresses { get; set; }
}
public class emailAddresses
{
public string emailAddress { get; set; }
public string emailAddress2 { get; set; }
}
I am doing a for-loop in the list and I need to get certain columns and put it in the array (I will put two, to keep it simple)
myEntities db = new myEntities();
List<rev_Result> revList = new List<rev_Result>();
revList.Clear();
revList = db.rev().ToList();
for (int i = 0; i < revList.Count(); i++)
{
Resas resas = new Resas();
profiles[] profiles = new profiles[1];
resas.todo = revList[i].todo;
resas.profiles[0].lastName = revList[i].lastName;
}
I am not familiar with C# as you can see from the psedo-code above.
I cannot figure out how to feed the Resas with data and then its Profile with data and then move to the next Resas entry.
Any help appreciated.
That's fairly simple using Linq:
Resas resas = new Resas();
resas.profiles = revList
.Select(x => new profiles() { action = x.todo, lastName = x.lastName })
.ToList();
What's happening here is: You loop through every entry in revList and get your wanted data structure (that's what Select is doing). x refers to the current entry in the loop, while the stuff to the right side of the arrow is you 'output': a new instance of your profiles class with the members assigned accordingly. The result of all of this is then converted to a list (before ToList(), think of it as a recipe to create the list) and assigned to resas.profiles.
By the way, a word on conventions: Usually, in C#, you would give your classes a name that starts with a capital letter. Also, your profiles class seems to contain data of exactly one profile, so a better name might be Profile. This also makes your data structure more clear, since List<profiles> seems to be a list of lists of profiles - but that's not what it actually is, is it?
Furthermore, Members generally start with a capital letter as well, so instead of action, lastName, you'd have: Action and LastName.
You can try with Linq. This is the code that should solve your issue, but Resas class doesn't have action property:
List<Resas> ls = revList.Select(x => new Resas() {
action = x.todo,
profiles = new List<profiles>() {
new profiles { lastName = x.lastName }
}
).ToList();
If you need to use action property of inprofiles` class:
List<Resas> ls = revList.Select(x => new Resas() {
profiles = new List<profiles>() {
new profiles {
action = x.todo,
lastName = x.lastName
}
}
).ToList();

Categories

Resources