Initializing a nested object which contains an array - c#

I have an object which I need to populate with some data. But when I try to populate the Party, I get a null reference error.
The object: https://pastebin.pl/view/f9f34c0e (Basically an object with 2 objects that contain an array of other objects)
Initializing:
Models.InHouse.TestSpec.InhouseOrder io = new Models.InHouse.TestSpec.InhouseOrder {
Header = new Models.InHouse.TestSpec.InhouseOrderHeader { Party = new Models.InHouse.TestSpec.InhouseOrderHeaderParty[10] },
content = new Models.InHouse.TestSpec.InhouseOrderContent { Item = new Models.InHouse.TestSpec.InhouseOrderContentItem[100] }};
But when I try to access io.header.Party[0].ID I get a Null Reference error. In the end, I will serialize it to a XML.

Well when you initialize like:
Party = new Models.InHouse.TestSpec.InhouseOrderHeaderParty[10]
Now the Party is an array of Models.InHouse.TestSpec.InhouseOrderHeaderParty with capacity of 10, but these 10 array items has the default value of Models.InHouse.TestSpec.InhouseOrderHeaderParty which is null.
You can later do something like:
for(int i=0; i< Party.Length; i++)
Party[i] = new Models.InHouse.TestSpec.InhouseOrderHeaderParty();
Update (Based on your comment):
You can intialize the array Items like:
Header = Enumerable.Range(1,10).Select(x => new Models.InHouse.TestSpec.InhouseOrderHeaderParty()).ToArray();

Related

Add items to array (C#)

I got some newCity:
ObservCity newCity = new ObservCity ()
{
id = localCityId,
entries = somecity.ToArray()
};
Now I load saved city:
ObservCity loadOldCity = await myService.loadCity(id);
How to add newCity.entries to loadOldCity.entries?
This don't work
newCity.entries.Concat(loadOldCity.entries);
//save newCity + loadOldCity
myService.saveCity(newCity);
You have not posted any class declarations, so I will take a guess and say entries is either an IEnumerable or an array, based on your current code. I will also assume the whole property is read-only. So you just create a new instance:
var updatedCity = new ObservCity
{
id = localCityId,
entries = newCity.entries.Concat(loadOldCity.entries).ToArray()
};
myService.saveCity(updatedCity);
You can add a range of items with the AddRange() method.
newCity.entries.AddRange(loadOldCity?.entries);

C# list of array type

I want to create a list of array type.
I want to create array containing values :
array = [a,b];
Then i want to put this array in list :
List<Array> list = new List<Array>( );
I am able to do this with list of string type but no luck with array type :
List<String> list = new List<String>( );
I am from javascript background, not much familiar with concept of collections in c#.
Also how can i create array in c# like we do in javascript :
var arrTemp = ["a", "b"];
Well, since your array is string[]:
var arrTemp = ["a", "b"];
you have to declare the required list as List<string[]>:
// list of string arrays
List<string[]> list = new List<string[]>() {
new string[] {"a", "b"}
};
In case you want to be able to put any array into the list declare it as loose as possible (List<object[]>):
// list of abitrary arrays
List<object[]> list = new List<object[]>() {
new string[] {"a", "b"},
new double[] {123.45, 789.12, 333.55},
new object[] {'a', "bcd", 1, 244.95, true},
};
Hope this can help you
var test = new List<int[]>();
You can actually create a list of arrays:
var listOfArrays = new List<Array>();
The problem with this is that it's difficult to use the arrays themselves, as the Array type doesn't support array syntax. (e.g. You can't do listOfArrays[0][0]) Instead, you have to use the GetValue method to do your retrieval:
var obj = listOfArrays[0].GetValue(0);
But this has another problem. The GetValue method returns object, so while you could always cast it to the desired type, you lose your type safety in choosing this approach.
Alternatively, you could just store object[] arrays:
var listOfArrays = new List<object[]>();
var obj = listOfArrays[0][0];
But while this solves the issue of the array notation, you still lose the type safety.
Instead, if at all possible, I would recommend finding a particular type, then just have arrays of that type:
var listOfArrays = new List<string[]>();
string s = listOfArrays[0][0];
for example, an array of strings would be
var arrayOfString = new string[]{"a","b"};
// or shorter form: string[] arrayOfString = {"a","b"};
// also: var arrayOfString = new[] { "a", "b" }
And then creating a list-of-arrayOfString would be
var listOfArrayOfString = new List<string[]>();
This works with any type, for example if you had a class MyClass
var arrayOfMyClass = new MyClass[]{ ... }; // ... is you creating instances of MyClass
var list = new List<MyClass[]>();

How to edit object array adding new data to set in C#

List<ChartView> data = new List<ChartView>();
var chartData = new object[data.length+1];
chartData[0] = new object[]
{
"Chart",
"Standard",
"BL"
};
int j = 0;
foreach (var i in data)
{
j++;
chartData[j] = new object[]
{
i.particulars,
i.originalDocuments,
i.filingOfEntries,
i.assessmentOfDuties,
i.paymentOfDuties,
i.releasing,
i.gatePass,
i.delivery
};
}
How can i add new data in object without deleting the old data. In the above code charttData[0] have 3 value Chart,Standard,BL. I need to add new string to the set of object. It should become Chart,Standard,BL,Sample.
I am working on dynamic line chart like this. The number of lines must be dynamic it could be 1,2 or morethan 10.
Please note that this question is not about Add new item in existing array in c#.net (which was earlier suggested as duplicate).
I try my best to understand your question, base on my understanding what your goal is to add new type of graph in your "object[] bla bla bla..." and each type of graph can use the content of data?
If my understanding is correct, I suggest to use Dictionary instead of confusing object array, by using Dictionary you can easily add new type of graph just like my example below:
List < ChartView > data = new List < ChartView > ();
Dictionary < string, List < ChartView >> graphType = new Dictionary < string, List < ChartView >> () {
{
"Chart", data
}, {
"Standard", data
}, {
"BL", data
}
}; // First you only have 3 kind of graphs.
grapType.Add("Sample", data); // this will allow you to add another graph named sample.
Note: This is just example how to use dictionary.

C# Declare multiple dynamically named variables [duplicate]

This question already has answers here:
How do I name variables dynamically in C#?
(9 answers)
Closed 8 years ago.
I'm not sure of the wording of what I'm looking for so I apologize if this has been answered since I'm new to C#.
What I'm trying to do is create multiple dynamically-named Lists based off of "i".
A code snippet would like this:
List<string> infoForUserSessions = new List<string>();
// Code that adds data to infoForUserSessions
for (int i = 0; i < infoForUserSessions.Count; i++){
// I want to initialize multiple List variables based off of how many users were found in my "infoForUserSessions" List.
List<string> user[i];
}
I was hoping it would create new Lists named:
user1
user2
user3
etc.
Update Sorry all for being so confusing. You guys swarmed with answers! Let me be more specific. I'm practicing string output from a Console application such as using "PsExec \localhost qwinsta". The output would look like this:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
services 0 Disc
>console mariob 1 Active
rdp-tcp 65536 Listen
Each line is stored in the List "infoForUserSessions" so the data looks like:
infoForUserSessions[0] = services 0 Disc
infoForUserSessions[1] = >console mariob 1 Active
infoForUserSessions[2] = rdp-tcp 65536 Listen
I then have code to pick out the important text out of each array index:
string[] tempStringArray;
List<string> allUsersAndIDs = new List<string>();
char[] delimiters = new char[] { ' ' };
foreach (string line in infoForUserSessions)
{
tempStringArray = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < tempStringArray.Length; i++)
{
// This is where I was thinking of some logic to create a new array for each user so I could store the separate parts of a string into this new array
// Something like (which would be from the Lists above in my original message--this is based off of how many users were stored in the original infoForUserSessions List:
// user1.Add(i);
}
}
I'm still working out the logic but I figured I wanted the output to be something dynamic based off of two factors:
How many "users" (strings) were stored in the List infoForUserSessions
Individual user arrays/Lists that have their own index values of:
.
user1[0] = "services";
user1[1] = "0";
user1[2] = "Disc";
user2[0] = ">console";
user2[1] = "mariob";
user2[2] = "1";
user2[2] = "Active";
Don't try to use dynamically named variables. That's simply not how variables work in C#.
Use an array of lists:
List<string>[] user = new List<string>[infoForUserSessions.Count];
for (int i = 0; i < infoForUserSessions.Count; i++) {
user[i] = new List<string>();
}
If the number of sessions can change, you would use a List<List<string>> instead, so that you can add lists to it when you add items to the infoForUserSessions list.
You can use Dictionary<String, List<string>>
Dictionary associate a key to a value, like an physical Dictionary book.
Dictionary<String, List<string>> myDict = new Dictionary<String, List<string>>();
for (int i = 0; i < infoForUserSessions.Count; ++i){
myDict.add("user" + i, new List<string>());
}
Here is an exemple how to use Dictionary :
Dictionary<String, String> myDict = new Dictionary<String, String>();
//Line below will add both KEY and a VALUE to the dictionary, BOTH are linked one to eachother
myDict.add("apple", "Apple is a brand");
//This above line return "Apple is a brand"
myDict["apple"];

LINQ and creating NON anonymous return values

I think I understand returning records of an anonymous type from But in this I want to create NEW CatalogEntries, and set them from the values selected. (context is a Devart LinqConnect database context, which lets me grab a view).
My solution works, but it seems clumsy. I want to do this in one from statement.
var query = from it in context.Viewbostons
select it;
foreach (GPLContext.Viewboston item in query)
{
CatalogEntry card = new CatalogEntry();
card.idx = item.Idx;
card.product = item.Product;
card.size = (long)item.SizeBytes;
card.date = item.Date.ToString();
card.type = item.Type;
card.classification = item.Classification;
card.distributor = item.Distributor;
card.egplDate = item.EgplDate.ToString();
card.classificationVal = (int)item.ClassificationInt;
card.handling = item.Handling;
card.creator = item.Creator;
card.datum = item.Datum;
card.elevation = (int)item.ElevationFt;
card.description = item.Description;
card.dirLocation = item.DoLocation;
card.bbox = item.Bbox;
card.uniqID = item.UniqId;
values.Add(card);
}
CatalogResults response = new CatalogResults();
I just tried this:
var query2 = from item in context.Viewbostons
select new CatalogResults
{ item.Idx,
item.Product,
(long)item.SizeBytes,
item.Date.ToString(),
item.Type,
item.Classification,
item.Distributor,
item.EgplDate.ToString(),
(int)item.ClassificationInt,
item.Handling,
item.Creator,
item.Datum,
(int)item.ElevationFt,
item.Description,
item.DoLocation,
item.Bbox,
item.UniqId
};
But I get the following error:
Error 79 Cannot initialize type 'CatalogService.CatalogResults' with a
collection initializer because it does not implement
'System.Collections.IEnumerable' C:\Users\ysg4206\Documents\Visual
Studio
2010\Projects\CatalogService\CatalogService\CatalogService.svc.cs 91 25 CatalogService
I should tell you what the definition of the CatalogResults is that I want to return:
[DataContract]
public class CatalogResults
{
CatalogEntry[] _results;
[DataMember]
public CatalogEntry[] results
{
get { return _results; }
set { _results = value; }
}
}
My mind is dull today, apologies to all. You are being helpful. The end result is going to be serialized by WCF to a JSON structure, I need the array wrapped in a object with some information about size, etc.
Since .NET 3.0 you can use object initializer like shown below:
var catalogResults = new CatalogResults
{
results = context.Viewbostons
.Select(it => new CatalogEntry
{
idx = it.Idx,
product = it.Product,
...
})
.ToArray()
};
So if this is only one place where you are using CatalogEntry property setters - make all properties read-only so CatalogEntry will be immutable.
MSDN, Object initializer:
Object initializers let you assign values to any accessible fields or properties of an
object at creation time without having to explicitly invoke a constructor.
The trick here is to create a IQueryable, and then take the FirstOrDefault() value as your response (if you want a single response) or ToArray() (if you want an array). The error you are getting (Error 79 Cannot initialize type 'CatalogService.CatalogResults' with a collection initializer because it does not implement 'System.Collections.IEnumerable') is because you're trying to create an IEnumerable within the CatalogEntry object (by referencing the item variable).
var response = (from item in context.Viewbostons
select new CatalogEntry()
{
idx = item.Idx,
product = item.Product,
size = (long)item.SizeBytes,
...
}).ToArray();
You don't have to create anonymous types in a Linq select. You can specify your real type.
var query = context.Viewbostons.Select( it =>
new CatalogEntry
{
idx = it.idx,
... etc
});
This should work:
var query = from it in context.Viewbostons
select new CatalogEntry()
{
// ...
};

Categories