NullReferenceException attempting to access a list located in a class? - c#
I am attempting to retrieve information using the Steam API. I created the classes offerStuff and itemsClass, offerStuff contains public List<itemsClass> items { get; set; }, however, whenever I attempt to access this list through os.items.Add(item), my program crashes with NullReferenceException. Is there some declaration I am missing? If so, how would I declare it so I can access it without the exception?
public static List<offerStuff> pollOffers()
{
using (dynamic tradeOffers = WebAPI.GetInterface("IEconService", config.API_Key))
{
List<offerStuff> OfferList = new List<offerStuff>();
offerStuff os = new offerStuff();
KeyValue kvOffers = tradeOffers.GetTradeOffers(get_received_offers: 1);//, active_only: 1
foreach (KeyValue kv in kvOffers["trade_offers_received"].Children)
{
os.tradeofferid = kv["tradeofferid"].AsInteger(); ;
os.accountid_other = Convert.ToUInt64(kv["accountid_other"].AsInteger());
os.message = kv["message"].AsString();
os.trade_offer_state = kv["trade_offer_state"].AsInteger();
foreach (KeyValue kv2 in kv["items_to_receive"].Children)
{
itemsClass item = new itemsClass();
item.appid = (kv2["appid"].AsInteger());
item.assetid = kv2["assetid"].AsInteger();
item.classid = kv2["classid"].AsInteger();
item.instanceid = kv2["instanceid"].AsInteger();
item.amount = kv2["amount"].AsInteger();
item.missing = kv2["missing"].AsInteger();
os.items.Add(item);
}
os.is_our_offer = kv["is_our_offer"].AsBoolean();
os.time_created = kv["time_created"].AsInteger();
os.time_updated = kv["time_updated"].AsInteger();
OfferList.Add(os);
}
return OfferList;
}
}
}
public class offerStuff
{
public int tradeofferid { get; set; }
public SteamID accountid_other { get; set; }
public string message { get; set; }
public int trade_offer_state { get; set; }
public List<itemsClass> items { get; set; }
public bool is_our_offer { get; set; }
public int time_created { get; set; }
public int time_updated { get; set; }
}
public class itemsClass
{
public int appid { get; set; }
public int assetid { get; set; }
public int classid { get; set; }
public int instanceid { get; set; }
public int amount { get; set; }
public int missing { get; set; }
}
The problem is probably that you're not initializing the collection items. You could do it on your contructor like this
public offerStuff()
{
items = new List<itemsClass>();
}
Related
Loop through a list of list assigning variables
I'm having trouble looping through my json trying to assign all my variables. I think it's because i don't get the loop through a list o list(Standings) to work. I'm sorry if my code is a bit messy with wierd variable names etc, but i have been going back and forth trying to figure it out but now i am at a point where i'm not know where i am anymore. I'm getting a JSON string from an API. This is stored in a variable named "body", and this string is Deserialized into a string called "json". All good at this point. But now i'm trying to loop through it all and assign values to all my variables. This is how my code look like: List<Standings> s = new List<Standings>(); var json = JsonConvert.DeserializeObject<Root>(body); // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(endpoint); var standing = json.api; //Console.WriteLine(standing.results.ToString()); foreach (var stand in standing.Standings) { var al = new All { matchsPlayed = stand.all.matchsPlayed, win = stand.all.win, draw = stand.all.draw, lose = stand.all.lose, goalsFor = stand.all.goalsFor, goalsAgainst = stand.all.goalsAgainst }; var ho = new Home { matchsPlayed = stand.home.matchsPlayed, win = stand.home.win, draw = stand.home.draw, lose = stand.home.lose, goalsFor = stand.home.goalsFor, goalsAgainst = stand.home.goalsAgainst }; var aw = new Away { matchsPlayed = stand.away.matchsPlayed, win = stand.away.win, draw = stand.away.draw, lose = stand.away.lose, goalsFor = stand.away.goalsFor, goalsAgainst = stand.away.goalsAgainst }; var standings = new List<Standings>(); foreach (var b in standing.Standings) { standings.Add(new Standings { rank = b.rank, team_id = b.team_id, teamName = b.teamName, logo = b.logo, group = b.group, forme = b.forme, status = b.status, description = b.description, all = al, home = ho, away = aw, goalsDiff = b.goalsDiff, points = b.points, lastUpdate = b.lastUpdate }); } s.Add(new Api { results = stand.results, Standings = al }); } This is all my properties, i think this is all correct: public partial class All { public int matchsPlayed { get; set; } public int win { get; set; } public int draw { get; set; } public int lose { get; set; } public int goalsFor { get; set; } public int goalsAgainst { get; set; } } public partial class Home { public int matchsPlayed { get; set; } public int win { get; set; } public int draw { get; set; } public int lose { get; set; } public int goalsFor { get; set; } public int goalsAgainst { get; set; } } public partial class Away { public int matchsPlayed { get; set; } public int win { get; set; } public int draw { get; set; } public int lose { get; set; } public int goalsFor { get; set; } public int goalsAgainst { get; set; } } public partial class Standings { public int rank { get; set; } public int team_id { get; set; } public string teamName { get; set; } public string logo { get; set; } public string group { get; set; } public string forme { get; set; } public string status { get; set; } public string description { get; set; } public All all { get; set; } public Home home { get; set; } public Away away { get; set; } public int goalsDiff { get; set; } public int points { get; set; } public string lastUpdate { get; set; } } public partial class Api { public int results { get; set; } public List<List<Standings>> Standings { get; set; } } public partial class Root { public Api api { get; set; } } This is the JSON i'm working with: {"api":{"results":1,"standings":[[{"rank":1,"team_id":45,"teamName":"Everton","logo":"https:\/\/media.api-sports.io\/football\/teams\/45.png","group":"Premier League","forme":"DWWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":4,"draw":1,"lose":0,"goalsFor":14,"goalsAgainst":7},"home":{"matchsPlayed":3,"win":2,"draw":1,"lose":0,"goalsFor":11,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":3,"goalsAgainst":1},"goalsDiff":7,"points":13,"lastUpdate":"2020-10-23"},{"rank":2,"team_id":66,"teamName":"Aston Villa","logo":"https:\/\/media.api-sports.io\/football\/teams\/66.png","group":"Premier League","forme":"WWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":4,"win":4,"draw":0,"lose":0,"goalsFor":12,"goalsAgainst":2},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":8,"goalsAgainst":2},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":4,"goalsAgainst":0},"goalsDiff":10,"points":12,"lastUpdate":"2020-10-23"},{"rank":3,"team_id":40,"teamName":"Liverpool","logo":"https:\/\/media.api-sports.io\/football\/teams\/40.png","group":"Premier League","forme":"DLWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":1,"lose":1,"goalsFor":13,"goalsAgainst":13},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":7,"goalsAgainst":4},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":6,"goalsAgainst":9},"goalsDiff":0,"points":10,"lastUpdate":"2020-10-23"},{"rank":4,"team_id":46,"teamName":"Leicester","logo":"https:\/\/media.api-sports.io\/football\/teams\/46.png","group":"Premier League","forme":"LLWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":12,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":8,"goalsAgainst":2},"goalsDiff":4,"points":9,"lastUpdate":"2020-10-23"},{"rank":5,"team_id":42,"teamName":"Arsenal","logo":"https:\/\/media.api-sports.io\/football\/teams\/42.png","group":"Premier League","forme":"LWLWW","status":"same","description":"Promotion - Europa League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":8,"goalsAgainst":6},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":4,"goalsAgainst":2},"away":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":4},"goalsDiff":2,"points":9,"lastUpdate":"2020-10-23"},{"rank":6,"team_id":39,"teamName":"Wolves","logo":"https:\/\/media.api-sports.io\/football\/teams\/39.png","group":"Premier League","forme":"WWLLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":5,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":2,"goalsAgainst":3},"away":{"matchsPlayed":3,"win":2,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":4},"goalsDiff":-2,"points":9,"lastUpdate":"2020-10-23"},{"rank":7,"team_id":47,"teamName":"Tottenham","logo":"https:\/\/media.api-sports.io\/football\/teams\/47.png","group":"Premier League","forme":"DWDWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":2,"lose":1,"goalsFor":15,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":0,"draw":2,"lose":1,"goalsFor":4,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":11,"goalsAgainst":3},"goalsDiff":7,"points":8,"lastUpdate":"2020-10-23"},{"rank":8,"team_id":49,"teamName":"Chelsea","logo":"https:\/\/media.api-sports.io\/football\/teams\/49.png","group":"Premier League","forme":"DWDLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":2,"lose":1,"goalsFor":13,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":6,"goalsAgainst":4},"goalsDiff":4,"points":8,"lastUpdate":"2020-10-23"},{"rank":9,"team_id":48,"teamName":"West Ham","logo":"https:\/\/media.api-sports.io\/football\/teams\/48.png","group":"Premier League","forme":"DWWLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":11,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":2},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":5},"goalsDiff":4,"points":7,"lastUpdate":"2020-10-23"},{"rank":10,"team_id":63,"teamName":"Leeds","logo":"https:\/\/media.api-sports.io\/football\/teams\/63.png","group":"Premier League","forme":"LDWWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":9,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":5,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":4},"goalsDiff":0,"points":7,"lastUpdate":"2020-10-23"},{"rank":11,"team_id":50,"teamName":"Manchester City","logo":"https:\/\/media.api-sports.io\/football\/teams\/50.png","group":"Premier League","forme":"WDLW","status":"same","description":null,"all":{"matchsPlayed":4,"win":2,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":4,"goalsAgainst":2},"goalsDiff":0,"points":7,"lastUpdate":"2020-10-23"},{"rank":12,"team_id":41,"teamName":"Southampton","logo":"https:\/\/media.api-sports.io\/football\/teams\/41.png","group":"Premier League","forme":"DWWLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":8,"goalsAgainst":9},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":5},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":4,"goalsAgainst":4},"goalsDiff":-1,"points":7,"lastUpdate":"2020-10-23"},{"rank":13,"team_id":34,"teamName":"Newcastle","logo":"https:\/\/media.api-sports.io\/football\/teams\/34.png","group":"Premier League","forme":"LWDLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":7,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":8},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":3,"goalsAgainst":1},"goalsDiff":-2,"points":7,"lastUpdate":"2020-10-23"},{"rank":14,"team_id":52,"teamName":"Crystal Palace","logo":"https:\/\/media.api-sports.io\/football\/teams\/52.png","group":"Premier League","forme":"DLLWW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":6,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":3,"goalsAgainst":3},"away":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":5},"goalsDiff":-2,"points":7,"lastUpdate":"2020-10-23"},{"rank":15,"team_id":33,"teamName":"Manchester United","logo":"https:\/\/media.api-sports.io\/football\/teams\/33.png","group":"Premier League","forme":"WLWL","status":"same","description":null,"all":{"matchsPlayed":4,"win":2,"draw":0,"lose":2,"goalsFor":9,"goalsAgainst":12},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":2,"goalsAgainst":9},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":7,"goalsAgainst":3},"goalsDiff":-3,"points":6,"lastUpdate":"2020-10-23"},{"rank":16,"team_id":51,"teamName":"Brighton","logo":"https:\/\/media.api-sports.io\/football\/teams\/51.png","group":"Premier League","forme":"DLLWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":1,"draw":1,"lose":3,"goalsFor":9,"goalsAgainst":11},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":3,"goalsAgainst":6},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":6,"goalsAgainst":5},"goalsDiff":-2,"points":4,"lastUpdate":"2020-10-23"},{"rank":17,"team_id":60,"teamName":"West Brom","logo":"https:\/\/media.api-sports.io\/football\/teams\/60.png","group":"Premier League","forme":"DLDLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":0,"draw":2,"lose":3,"goalsFor":5,"goalsAgainst":13},"home":{"matchsPlayed":3,"win":0,"draw":2,"lose":1,"goalsFor":3,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":2,"goalsAgainst":7},"goalsDiff":-8,"points":2,"lastUpdate":"2020-10-23"},{"rank":18,"team_id":44,"teamName":"Burnley","logo":"https:\/\/media.api-sports.io\/football\/teams\/44.png","group":"Premier League","forme":"DLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":4,"win":0,"draw":1,"lose":3,"goalsFor":3,"goalsAgainst":8},"home":{"matchsPlayed":1,"win":0,"draw":0,"lose":1,"goalsFor":0,"goalsAgainst":1},"away":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":3,"goalsAgainst":7},"goalsDiff":-5,"points":1,"lastUpdate":"2020-10-23"},{"rank":19,"team_id":62,"teamName":"Sheffield Utd","logo":"https:\/\/media.api-sports.io\/football\/teams\/62.png","group":"Premier League","forme":"DLLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":5,"win":0,"draw":1,"lose":4,"goalsFor":2,"goalsAgainst":7},"home":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":1,"goalsAgainst":4},"away":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":1,"goalsAgainst":3},"goalsDiff":-5,"points":1,"lastUpdate":"2020-10-23"},{"rank":20,"team_id":36,"teamName":"Fulham","logo":"https:\/\/media.api-sports.io\/football\/teams\/36.png","group":"Premier League","forme":"DLLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":5,"win":0,"draw":1,"lose":4,"goalsFor":4,"goalsAgainst":12},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":0,"goalsAgainst":6},"away":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":4,"goalsAgainst":6},"goalsDiff":-8,"points":1,"lastUpdate":"2020-10-23"}]]}} I'm new to c# and object orienting programming but i'm pretty sure it's the List of list "standing" that's confusing it to me.
Assign values from one model to another without checking null values each time
I need to assign values from one model to another only if values aren't null. How can I simplify the code below? What pattern should I use? DatabaseModel databaseModel = new DatabaseModel(); databaseModel.DatabaseModelProperty1 = 1; databaseModel.DatabaseModelProperty1 = 2; ContractModel contractModel = new ContractModel(); contractModel.ContractProperty1 = 5; contractModel.ContractProperty2 = new ContractModel.InnerContractModel_1(); contractModel.ContractProperty2.InnerContract_1Property1 = 10; // each time I need to write if and check null values: if (contractModel.ContractProperty1.HasValue) { databaseModel.DatabaseModelProperty1 = contractModel.ContractProperty1.Value; } if (contractModel.ContractProperty2 != null) { if (contractModel.ContractProperty2.InnerContract_1Property1.HasValue) { databaseModel.DatabaseModelProperty2 = contractModel.ContractProperty2.InnerContract_1Property1.Value; } if (contractModel.ContractProperty2.InnerContract_1Property2.HasValue) { databaseModel.DatabaseModelProperty3 = contractModel.ContractProperty2.InnerContract_1Property2.Value; } } // .......... My first model: public class DatabaseModel { public int DatabaseModelProperty1 { get; set; } public int DatabaseModelProperty2 { get; set; } public int DatabaseModelProperty3 { get; set; } public int DatabaseModelProperty4 { get; set; } public int DatabaseModelProperty5 { get; set; } } My second model: public class ContractModel { public int? ContractProperty1 { get; set; } public InnerContractModel_1 ContractProperty2 { get; set; } public InnerContractModel_2 ContractProperty3 { get; set; } public class InnerContractModel_1 { public int? InnerContract_1Property1 { get; set; } public int? InnerContract_1Property2 { get; set; } } public class InnerContractModel_2 { public int? InnerContract_2Property1 { get; set; } public int? InnerContract_2Property2 { get; set; } } } Any ideas? I don't want to check each time null values but I have no idea what I should change.
Executing Actions within Actions for collection without creating new collection
I have collection of objects where each object contains other collections of objects. All I want to modify my original collection of objects in a way, that no extra memory should be allocated. Everything should happen in memory. I am looking for some templatized Action or Func so that with the mixture of declarative and functional approach, no new collection is formed and in memory my original collection is also modified. Following is the hierarchy of collection public class ConsignmentAddress { public int ConsignmentAddressId { get; set; } public int AddressTypeId { get; set; } public string Street { get; set; } public string Town { get; set; } public string ZipCode { get; set; } public int ConsignmentId { get; set; } } public class ConsignmentLine { public int ConsignmentLineId { get; set; } public int PackagingId { get; set; } public double Amount { get; set; } public double Weight { get; set; } public int ConsignmentId { get; set; } public int? PackagingAidId { get; set; } } public class PackagingAid { public int PackagingAidId { get; set; } public int ConsignmentId { get; set; } public int PackagingId { get; set; } public double Quantity { get; set; } } public class Consignment { public int ConsignmentId { get; set; } public int ClientSubsidiaryId { get; set; } public int ForwarderId { get; set; } public int Sourcepaty { get; set; } public int ParentId { get; set; } public int ProductId { get; set; } public ICollection<PackagingAid> PackagingAids { get; set; } public ICollection<ConsignmentLine> ConsignmentLines { get; set; } public ICollection<ConsignmentAddress> ConsignmentAddresses { get; set; } public Consignment() { PackagingAids = new List<PackagingAid>(); ConsignmentLines = new List<ConsignmentLine>(); ConsignmentAddresses = new List<ConsignmentAddress>(); } } My intention is to write generic extension method which should operate on all kind of objects in the hierarchy I mentioned above. public static class ConsignmentExtension { public static T Set<T>(this T input, Action<T> updater) { updater(input); return input; } } Where as my client code is which is first getting list of 10000 of objects in list and just resetting few properties of ( consignment, consignmentaddresses for corresponding consignment, consignmentlines of corresponding consignment and packagingaid of corresponding consignment) My written Foreach approach worked fine but i want templatized and efficient approach for the same collection. consignments.ForEach(cons => { cons.ConsignmentId = -1; cons.ConsignmentAddresses.ToList().ForEach(address => { address.ConsignmentId = -1; address.ConsignmentAddressId = -1; }); cons.ConsignmentLines.ToList().ForEach(line => { line.ConsignmentId = -1; line.ConsignmentLineId = -1; line.PackagingAidId = -1; }); cons.PackagingAids.ToList().ForEach(aid => { aid.ConsignmentId = -1; aid.PackagingAidId = -1; }); }); But I am looking for something like declarative style. var updatedConsignments = from consignment in consignments select consignment.Set<Consignment>(con => { con.ConsignmentId = -1; con.ConsignmentAddresses.Set<dynamic>(address => { address.ConsignmentId = -1; address.ConsignmentAddressId = -1; }); con.ConsignmentLines.Set<dynamic>(line => { line.PackagingAidId = -1; line.ConsignmentId = -1;line.ConsignmentLineId = -1; }); con.PackagingAids.Set<dynamic>(aid => { aid.ConsignmentId = -1; aid.PackagingAidId = -1; }); }); Is that possible somehow? Thanks in advance.
This could be written as public static class ConsignmentExtension { public static IEnumerable<dynamic> SetEach(this IEnumerable<dynamic> input, Action<dynamic> updater) { foreach (var item in input) { updater(item); } return input; } } Usage: var addresses = new [] { new ConsignmentAddress() }; addresses.SetEach(a => a.ConsignmentId = -1); var packages = new [] { new PackagingAid() }; packages.SetEach(p => p.PackagingAidId = -1);
Can not access object's properties inside my view model
I have added the following two model view classes: public class AssetCount { public int CustomerCount { get; set; } public int DataCenterCount { get; set; } public int FirewallCount { get; set; } public int RouterCount { get; set; } public int VirtualMachineCount { get; set; } public int ServerCount { get; set; } public int StorageDeviceCount { get; set; } public int RackCount { get; set; } public int SwitchCount { get; set; } public int CustomCount { get; set; } } public class SystemInformation { public AssetCount AssetCount { get; set; } public ICollection<TechnologyAudit> TechnologyAudit { get; set; } public ICollection<AdminAudit> AdminAudit { get; set; } public ICollection<Technology> LatestTechnology { get; set; } } But, inside my model class method, I was unable to access the AssetCount object's properties, such as: public SystemInformation GetSystemInfo(int pagesize) { SystemInformation s = new SystemInformation() { AssetCount.CustomerCount = entities.AccountDefinitions.Count() //I can not access the CustomerCount !!!! So can anyone advise me what the problem is? Thanks.
You have to initialize AssetCount property first: SystemInformation s = new SystemInformation() { AssetCount = new AssetCount { CustomerCount = entities.AccountDefinitions.Count() } };
Using Linq to pass data from one collection to another
I want to use LINQ to pass data from one custom collection to another. Its complicated because the collection has 2 sub collections. Want to copy data to: public class Quote { public int Id { get; set; } public string Type { get; set; } public virtual ICollection<Rate> Rates { get; set; } } public class Rate { public int Id { get; set; } public virtual ICollection<Option> Options { get; set; } } public class Option { public int Id { get; set; } public decimal Price { get; set; } } from: public class Quote { public int QuoteId { get; set; } public string Type { get; set; } public string Destination { get; set; } public List<RateSet> RateSets { get; set; } } public class RateSet { public int Id { get; set; } public decimal ValueMin { get; set; } public decimal ValueMax { get; set; } public List<Option> Options { get; set; } } public class Option { public int Id { get; set; } public string Name { get; set; } public decimal? Price { get; set; } } I was getting somewhere with this but keeping hitting problems... newQuotes = Quotes .Select(x => new Quote() { Id = x.QuoteId, Rates = x.RateSets.Select( y => new Rate() { Id = y.Id, Options = y.Options.Select(z => new Option() { Id = z.Id, Price = z.Price }).ToList(),.... to
Compiled without any errors // to public class Quote2 { public int Id { get; set; } public string Type { get; set; } public virtual ICollection<Rate> Rates { get; set; } } public class Rate { public int Id { get; set; } public virtual ICollection<Option2> Options { get; set; } } public class Option2 { public int Id { get; set; } public decimal Price { get; set; } } // from public class Quote1 { public int QuoteId { get; set; } public string Type { get; set; } public string Destination { get; set; } public List<RateSet> RateSets { get; set; } } public class RateSet { public int Id { get; set; } public decimal ValueMin { get; set; } public decimal ValueMax { get; set; } public List<Option1> Options { get; set; } } public class Option1 { public int Id { get; set; } public string Name { get; set; } public decimal? Price { get; set; } } void Main() { var Quotes = new List<Quote1>(); var newQuotes = Quotes .Select(x => new Quote2 { Id = x.QuoteId, Rates = x.RateSets == null ? null : x.RateSets.Select( y => new Rate { Id = y.Id, Options = y.Options == null ? null : y.Options.Select(z => new Option2 { Id = z.Id, Price = z.Price.Value }).ToList()}).ToList()}).ToList(); }
I would make it a bit more modular: newQuotes = Quotes.Select(x => new Quote { ID = x.QuoteID, Type = x.Type, Rates = ConvertRates(x.RateSets) }); ConvertRates would use the same approach to create its sub objects and could either be a method or a Func: ICollection<Rate> ConvertRates(IEnumerable<RateSet> oldRates) { return oldRates.Select(x => new Rate { ID = x.ID, Options = ConvertOptions(x.Options) }).ToList(); } Basically, this is the same approach you used, just split up and readable.
I think what you need to do is define casting between each two corresponding classes, then cast one list into the other.
A simpler way may be to create methods in each class that would convert itself to the other type. Or if you don't want that kind of coupling, create a factory class that will do the conversion for you, one item at a time. Then use link to loop through and convert each item. Like so: public class Quote { public int Id { get; set; } public string Type { get; set; } public virtual ICollection<Rate> Rates { get; set; } public static Quote FromData(Data.Quote input){ if (input == null) return null; Quote output = new Quote() { Id = input.QuoteId, Type = input.Type }; output.Rates = (from i in input.RateSets select Rate.FromData(i)).ToList(); } } public class Rate { public int Id { get; set; } public virtual ICollection<Option> Options { get; set; } public static Rate FromData(Data.RateSet input) { if (input == null) return null; Rate output = new Rate() { Id = input.Id }; output.Options = (from i in input.Options select Option.FromData(i)).ToList(); return output; } } public class Option { public int Id { get; set; } public decimal Price { get; set; } public static Option FromData(Data.Option input) { if (input == null) return null; Option output = new Option() { Id = input.Id, Price = input.Price ?? 0m }; return output; } } namespace Data { public class Quote { public int QuoteId { get; set; } public string Type { get; set; } public string Destination { get; set; } public List<RateSet> RateSets { get; set; } } public class RateSet { public int Id { get; set; } public decimal ValueMin { get; set; } public decimal ValueMax { get; set; } public List<Option> Options { get; set; } } public class Option { public int Id { get; set; } public string Name { get; set; } public decimal? Price { get; set; } } }