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.
Related
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();
So let's say that you have 2 series of data. (Both object arrays, in your choice of a serialized JSON string, or the actual objects).
For Instance:
string str1 = #"{""datapoints"":[[""02/28/2019"",146800.0],[""02/27/2019"",147700.0],[""02/26/2019"",153900.0]]}";
Then, you have a second series that is very similar...
string str2 = #"{""datapoints"":[[""02/28/2019"",145600.0],[""02/27/2019"",143600.0],[""02/26/2019"",152200.0]]}";
Note: the object arrays inside are both a length of "2", and both contain the same "date" as the [0] index.
How does one merge the 2 object arrays into 1, to yield the following output...
string str3 = #"{""datapoints"":[[""02/28/2019"",145600.0,145600.0],[""02/27/2019"",143600.0,143600.0],[""02/26/2019"",152200.0,152200.0]]}";
For clarity, I'm interested in using the [0] index once, and merging the [1] indexes together. (the number values)
Extra credit if this can be a loop, or can be done with any number of series.
Using json.net, you can deserialize each JSON sample to an object that contains a datapoints property that is an enumerable of object arrays, then merge them using the LINQ methods GroupBy() and Aggregate().
Say the JSON samples to be merged are in a string [][] jsonSeriesList like so:
string str1 = #"{""datapoints"":[[""02/28/2019"",146800.0],[""02/27/2019"",147700.0],[""02/26/2019"",153900.0]]}";
string str2 = #"{""datapoints"":[[""02/28/2019"",145600.0],[""02/27/2019"",143600.0],[""02/26/2019"",152200.0]]}";
var jsonSeriesList = new[] { str1, str2 }; // Add others as required
Then you can create a combined series as follows:
var merged = jsonSeriesList.Aggregate(
new { datapoints = Enumerable.Empty<object[]>() },
(m, j) => new
{
datapoints = m.datapoints.Concat(JsonConvert.DeserializeAnonymousType(j, m).datapoints)
// Group them by the first array item.
// This will throw an exception if any of the arrays are empty.
.GroupBy(i => i[0])
// And create a combined array consisting of the key (the first item from all the grouped arrays)
// concatenated with all subsequent items in the grouped arrays.
.Select(g => new[] { g.Key }.Concat(g.SelectMany(i => i.Skip(1))).ToArray())
});
var mergedJson = JsonConvert.SerializeObject(merged);
Notes:
I am deserializing to an anonymous type for brevity. You could create an explicit data model if you prefer.
I am assuming the individual datapoint arrays all have at least one item.
There is no attempt to sort the resulting merged JSON by series date. You could do that if necessary.
The solution assumes that you will never have multiple component arrays in the same series with the same first item, e.g. "02/28/2019" repeated twice. If so, they will get merged also.
Sample .Net fiddle here.
Here is a simplified example (simplified as validations might be required, but hope it given you a place to start):
Convert it into dot net object
Then go through each date point - for each date point go through all the series, adding the values.
//container object for the json series
public class Container
{
public List<List<object>> datapoints;
}
//Input series in JSON
string[] inputSeries = new string[]
{
"{\"datapoints\": [[\"02/28/2019\", 146800.0],[\"02/27/2019\", 147700.0],[\"02/26/2019\", 153900.0]]}",
"{\"datapoints\": [[\"02/28/2019\", 145600.0],[\"02/27/2019\", 143600.0],[\"02/26/2019\", 152200.0]]}"
};
//Container for input series in dot net object
List<Container> con = new List<Container>();
foreach (var series in inputSeries)
{
con.Add(JsonConvert.DeserializeObject<Container>(series));
}
// output container
Container output = new Container();
output.datapoints = new List<List<object>>();
// assuming all series have equal number of data points.....might not be so
for (int i = 0; i < con[0].datapoints.Count; i++)
{
output.datapoints.Add(new List<object>());
// inner loop is to go across series for the same datapoint....
for (int j = 0; j < con.Count; j++)
{
// add the date if this is the first series....after that only add the values
// right now the assumption is that the dates are in order and match....validation logic might be required
if (j == 0)
{
output.datapoints[i].Add(con[j].datapoints[i][0]);
output.datapoints[i].Add(con[j].datapoints[i][1]);
}
else
{
output.datapoints[i].Add(con[j].datapoints[i][1]);
}
}
}
I simply worked with Transaction in ArnagoDB_NET when I work with one item of my model. but I have a problem when I want to pass a list of my model.
var transactionResult= Context.Transaction.WriteCollection("User").Execute<Dictionary<string, object>>(
string.Format(#"
function () {{
var db = require('internal');
if(!db.User.exists('{0}'))
db.User.save( {{ _key:'{0}', UserAppState:1 }});
}}
// and other actions
return {{ 'Executed': true }};
}}", myModel.userId))
above example fine worked, but when I want to pass a list of my model, how can I iterate them into string(or ArangoDB script)?
for example:
string.Format(#"
function () {{
var db = require('internal');
for (i = 0; i < {0}.count; i++){{ // I know didn't work this block code!
if(!db.User.exists('{i.key}'))
db.User.save( {{ _key: ""'i.key'"", UserAppState:1 }});
// and other actions
}}
return {{ 'Executed': true }};
}}", lstMyModels);
can any one help me?!
I don't think this would be possible given your example, since you are combining C# string interpolated object with ArangoDB transaction functionality which doesn't work together just by combining them into single query.
Your first example works because it's using primitive value which you pass into the string, however in the second example you want to pass list of objects and iterate through them using cycle that is not in any way connected to the list itself. This line
for (i = 0; i < {0}.count; i++) {
won't work because lstMyModels is a C# list object and you would actually end up with a string interpolated like this:
for (i = 0; i < System.Collections.Generic.List`1[System.Object].count; i++) {
which makes no sense to the ArangoDB which needs to execute the transaction. Moreover the i variable is a simple number serving as current cycle iteration index therefore calling i.key is also wrong.
Instead of complicated string interpolation you should try to use transaction parameter passing which is supported by the ArangoDB-NET driver.
EDIT:
Let's say you have object like this:
public class TransactionEntity
{
public string Foo { get; set; }
}
Then you can pass it as transaction parameter for example like this:
var transactionData = new List<TransactionEntity>
{
new TransactionEntity
{
Foo = "string1"
},
new TransactionEntity
{
Foo = "string2"
},
new TransactionEntity
{
Foo = "string3"
}
};
var transactionResult = db.Transaction
.WriteCollection("myCollection")
.Param("data", transactionData)
.Execute<List<TransactionEntity>>(#"
function (params) {
var db = require('internal').db;
for (var i = 0; i < params.data.length; i++) {
db.myCollection.save(params.data[i]);
}
return db._query('FOR doc IN myCollection SORT TO_NUMBER(doc._key) RETURN doc').toArray();
}
");
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"];
I want to return a sublist of object and Total size of the Original List.
in this case can i use MAP .
Example :-
Map<Integer,String> sample(){
List<String> list = new ArrayList<String>(0);
for(i=0;i<50;i++)
list.add(i+"");
List<String> sublist = list.sublist(0,10);
Integer totalsize = list.size();
Map<Integer,String> map = new Hashmap<Integer,List>(0);
map.put(totalsize,sublist);
return map;
}
otherwise can i return one POJO Object fro returning these information to calling function.
I need a performance wise guidance on this .
If you are using C#, you can use the ArraySegment<T> structure. It contains a reference of the original array too. You can find the details here in msdn
You need a Map to store the sublist and size of the original list with two different keys, here is the code in java to meet the req...
Map<Integer, String> sample() {
Map map = new HashMap();
List<String> list = new ArrayList<String>(0);
for ( int i = 0; i < 50; i++)
list.add(i + "");
List<String> sublist = list.subList(0, 10);
Integer totalsize = list.size();
map.put("sublist", sublist);
map.put("original_list_length", totalsize);
return map;
}