c# Getting the Index from an array inside a JSon Object - c#

I'm trying to find out the index of a string in an array within a JObject object. For example, you could give frc610 and it would return 0.
// Get rankings JSON file from thebluealliance.com
string TBArankings = #"https://www.thebluealliance.com/api/v2/district/ont/2017/rankings?X-TBA-App-Id=frc2706:ONT-ranking-system:v01";
var rankings = new WebClient().DownloadString(TBArankings);
string usableTeamNumber = "frc" + teamNumberString;
string team_key = "";
int rank = 0;
dynamic arr = JsonConvert.DeserializeObject(rankings);
foreach (dynamic obj in arr)
{
team_key = obj.team_key;
rank = obj.rank;
}
int index = Array.IndexOf(arr, (string)usableTeamNumber); // <-- This is where the exception is thrown.
Console.WriteLine(index);
// Wait 20 seconds
System.Threading.Thread.Sleep(20000);
Here's the json file I'm using.
I've tried multiple different solutions, none of which worked.

You could just keep the index in variable.
string usableTeamNumber = $"frc{teamNumberString}";
string team_key = "";
int rank = 0;
int index = 0;
int count = 0;
dynamic arr = JsonConvert.DeserializeObject(rankings);
foreach (dynamic obj in arr)
{
team_key = obj.team_key;
rank = obj.rank;
if (usableTeamNumber.Equals(team_key) {
index = count;
}
count++;
}
Console.WriteLine(index);

Create a class that mimics your data structure, like such (only has 3 of the root fields):
public class EventPoints
{
public int point_total { get; set; }
public int rank { get; set; }
public string team_key { get; set; }
}
Then you can Deserialize the object into a list of those objects and you can use LINQ or other tools to query that list:
string teamNumberString = "frc2056";
string TBArankings = #"https://www.thebluealliance.com/api/v2/district/ont/2017/rankings?X-TBA-App-Id=frc2706:ONT-ranking-system:v01";
var rankings = new WebClient().DownloadString(TBArankings);
List<EventPoints> eps = JsonConvert.DeserializeObject<List<EventPoints>>(rankings);
EventPoints sp = eps.Where(x => x.team_key.Equals(teamNumberString)).FirstOrDefault();
Console.WriteLine(eps.IndexOf(sp));
Console.ReadLine();

Related

Load a list from an array

I have a program that is working except that my data is contained in an array; however, I have found out from you people that I cannot load a dataGridView from an array.
If I had code like this, how would I load a List for the source of the dataGridView1...
// Load some date to indicate what I'm trying to do.
int nColName = 0;
int nColNumberOfOccurances = 1;
int nColTotalTime = 2;
int nColAverageTime = 3;
string[,] strMyArray = new string[2,4];
// load array with test data
for (int i = 0; i < strMyArray.Length; i++)
{
switch (i)
{
case 0:
strMyArray.SetValue("file1.log".ToString(), i, nColName);
strMyArray.SetValue("10".ToString(), i, nColNumberOfOccurances);
strMyArray.SetValue("8989".ToString(), i, nColTotalTime);
strMyArray.SetValue("898.9".ToString(), i, nColAverageTime);
break;
case 1:
strMyArray.SetValue("file2.log".ToString(), i, nColName);
strMyArray.SetValue("5".ToString(), i, nColNumberOfOccurances);
strMyArray.SetValue("4494.5".ToString(), i, nColTotalTime);
strMyArray.SetValue("898.9".ToString(), i, nColAverageTime);
break;
}
}
// convert an array like the above into a List so that I can say...
// myNewListFromArray = strMyArray
// dataGridView1.DataSource = myNewListFromArray;
Arrays works with DataGridView. Your problems is - you using two dimensional array which cannot be used as DataSource.
Instead of array, create a class with properties which represent your data.
Note: important to use a property, because DataGridView binding works with properties only.
public class MyData
{
public string Name { get; set; }
public string NumberOfOccurances { get; set; }
public string TotalTime { get; set; }
public string AverageTime { get; set; }
}
Then use this class in the List
var list = new List<MyData>
{
new MyData
{
Name = "file1.log",
NumberOfOccurances = "10",
TotalTime = "8989",
AverageTime = "898.9"
},
new MyData
{
Name = "file2.log",
NumberOfOccurances = "5",
TotalTime = "4494.5",
AverageTime = "898.9"
},
}
dataGridView1.DataSource = list;

C# How do I create an array/matrix that stores the data?

My file looks like this:
hello,1,2,up
goodbye,0,4,down
...
I have WordToFind which will have the first word from my file, but I want it to have both the words 'hello' and 'goodbye'.
Same for X1Coordinate, I want it to have '1' and '0', but as integers.
So how can I modify my code to do that?
I'm a beginner and I tryed to figure it out for over 3 hours and still didn't manage, so I'm sorry if it's a really basic question.
for (int m = 0; m < Words; m++)
{
string LinesInFile = reader.ReadLine();
string[] WordsWithSpecifics = LinesInFile.Split(',');
string WordToFind = WordsWithSpecifics[0];
int X1Coordinate = int.Parse(WordsWithSpecifics[1]);
int Y1Coordinate = int.Parse(WordsWithSpecifics[2]);
string WordDirection = WordsWithSpecifics[3];
Now I get what you need. Below code will do what you require:
var WordToFind = new List<string>();
var X1Coordinate = new List<int>();
var Y1Coordinate = new List<int>();
var WordDirection = new List<string>();
while((LinesInFile = reader.ReadLine()) != null)
{
string[] WordsWithSpecifics = LinesInFile.Split(',');
WordToFind.Add(WordsWithSpecifics[0]);
X1Coordinate.Add(int.Parse(WordsWithSpecifics[1]));
Y1Coordinate.Add(int.Parse(WordsWithSpecifics[2]));
WordDirection.Add(WordsWithSpecifics[3]);
}
But I personally recommend using a class for storing structured data like this:
class MyDataType
{
public string Word { get; set; }
public int X1 { get; set; }
public int Y1 { get; set; }
public string Direction { get; set; }
}
Then use it like this:
var myData = new List<MyDataType>()
while((LinesInFile = reader.ReadLine()) != null)
{
string[] WordsWithSpecifics = LinesInFile.Split(',');
myData.Add(new MyDataType(){
Word = WordsWithSpecifics[0],
X1 = int.Parse(WordsWithSpecifics[1]),
Y1 = int.Parse(WordsWithSpecifics[2]),
Direction = WordsWithSpecifics[3]
};
}

C# Access value from serialized json array

I have a simple serialized json array
string json = "[{\"id\":100,\"UserId\":99},{\"id\":101,\"UserId\":98}]";
var data = (List<Model>)Newtonsoft.Json.JsonConvert.DeserializeObject(json , typeof(List<Model>));
my model to deserialize:
public class Model
{
public int? id { get; set; }
public int? UserId { get; set; }
}
What is the best way to retrieve data from each Index[?] and print it to Console ?
You can do a foreach loop:
foreach(var item in data) {
Console.WriteLine(item.UserId);
}
string json = "[{\"id\":100,\"UserId\":99},{\"id\":101,\"UserId\":98}]";
var objects = JArray.Parse(json);
var firstIndexValue = objects[0];
Console.WriteLine(firstIndexValue);
foreach (var index in objects)
{
Console.WriteLine(index);
}
for (int index = 0; index < objects.Count; index++)
{
Console.WriteLine(objects[index]);
}

Sort text file data into an array

I'm working on a homework problem for my computer science class. A cities census data is on a text file holding records for its citizens. Each line will have four fields(age, gender, marital status, and district) of different data types separated by a comma. For example, 22, F, M, 1.
How should I approach this? My thoughts are that I should use two 1D arrays, one for age and one for district. I need to be able to later count how many people are in each district, and how many people are in different age groups for the whole city.
How do I read each line and get the info I want into each array?
edit**
This is what I've managed to do so far. I'm trying to separate my data from fields into four different arrays. This is where I'm stuck.
FileStream fStream = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(fStream);
string inputRecord = "";
string[] fields;
int[] ageData = new int[1000];
string[] genderData = new string[1000];
string[] maritalData = new string[1000];
int[] districtData = new int[1000];
inputRecord = inFile.ReadLine();
while (inputRecord != null)
{
fields = inputRecord.Split(',');
int i = 0;
ageData[i] = int.Parse(fields[0]);
genderData[i] = fields[1];
maritalData[i] = fields[2];
districtData[i] = int.Parse(fields[3]);
i++;
inputRecord = inFile.ReadLine();
}
edit 2**
First question, I've decided to use the below code to find out how many citizens are in each district of the census data.
for (int x = 1; x <= 22; x++)
for (int y = 0; y < districtData.Length; y++)
if (districtData[y] == x)
countDist[x]++;
for (int x = 1; x <= 22; x++)
Console.WriteLine("District " + x + " has " + countDist[x] + " citizens");
In my .Writeline when x reaches two digits it throws off my columns. How could I line up my columns better?
Second question, I am not quite sure how to go about separating the values I have in ageData into age groups using an if statement.
It sounds like each of the four fields have something in common... they represent a person surveyed by the census. That's a good time to use a class along the lines of
public class Person
{
public int Age { get; set; }
public string Gender { get; set; }
public string MaritalStatus { get; set; }
public int District { get; set; }
}
Then, just read in all of the lines from the text file (if it's small, it's fine to use File.ReadAllLines()), and then create an instance of Person for each line in the file.
You can create a
List<Person> people;
to hold the Person instances that you parse from the text file.
Since the lines appear to be separated by commas, have a look at String.Split().
UPDATE
The attempt in your edit is pretty close. You keep creating a new i and initializing it to 0. Instead, initialize it outside your loop:
int i = 0;
while (inputRecord != null)
{
fields = inputRecord.Split(',');
Also you may want to trim excess spaces of of your input. If the fields are separated with ", " rather than just "," you will have excess spaces in your fields.
genderData[i] = fields[1].Trim();
maritalData[i] = fields[2].Trim();
How about this?
List<string[]> o = File.ReadAllLines(#"C:\TestCases\test.txt").Select(x => x.Split(',')).OrderBy(y => y[0]).ToList();
Each person is a string array in the list.
Each property is a index in the array eg: age is first.
The above code reads all lines comma delimits them orders them by age and adds them to the list.
public static class PersonsManager
{
public static PersonStatistics LoadFromFile(string filePath)
{
var statistics = new PersonStatistics();
using (var reader = new StreamReader(filePath))
{
var separators = new[] { ',' };
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line))
continue; //--malformed line
var lParts = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);
if (lParts.Length != 4)
continue; //--malformed line
var person = new Person
{
Age = int.Parse(lParts[0].Trim()),
Gender = lParts[1].Trim(),
MaritalStatus = lParts[2].Trim(),
District = int.Parse(lParts[3].Trim())
};
statistics.Persons.Add(person);
}
}
return statistics;
}
}
public class PersonStatistics
{
public List<Person> Persons { get; private set; }
public PersonStatistics()
{
Persons = new List<Person>();
}
public IEnumerable<Person> GetAllByGender(string gender)
{
return GetByPredicate(p => string.Equals(p.Gender, gender, StringComparison.InvariantCultureIgnoreCase));
}
//--NOTE: add defined queries as many as you need
public IEnumerable<Person> GetByPredicate(Predicate<Person> predicate)
{
return Persons.Where(p => predicate(p)).ToArray();
}
}
public class Person
{
public int Age { get; set; }
public string Gender { get; set; }
public string MaritalStatus { get; set; }
public int District { get; set; }
}
Usage:
var statistics = PersonsManager.LoadFromFile(#"d:\persons.txt");
var females = statistics.GetAllByGender("F");
foreach (var p in females)
{
Console.WriteLine("{0} {1} {2} {3}", p.Age, p.Gender, p.MaritalStatus, p.District);
}
I hope it helps.

Get string value and add to specific variables

I want to get the value in an array and i want to put it in a variable
This is the array {1,eli}
CsvValues = RowData.Split(new string[] {","},
StringSplitOptions.RemoveEmptyEntries); // RowData is {1,eli}
List<string> elements = new List<string>();
foreach (string data in CsvValues)
{
elements.Add(data);
}
and then I want to put it here:
result.Add(new wsSample()
{
id = elements[0],
name = elements[1]
});
How will i add the elements value to id and name?
public class wsSample
{
[DataMember]
public string id { get; set; }
[DataMember]
public string name { get; set; }
}
How is the rest of the input array structured?
If it is elements = {"1","eli", "2","manning"}
then you might be better off using a for loop.
I think this is what you are looking for
List<wsSample> samples = new List<wsSample>();
for(int i=0; i< elements.length-1; ++i)
{
samples.Add(new wsSample()
{
id = elements[i]
name = elements[i+1]
});
i= i+2;
}

Categories

Resources