Write Json file with new line order using C# - c#

I am writing a code throug which I can serialize a JSON file with multiple data like shorttext,Geocoordinates, and image. But after generating it will show in a big line. But I want to organize it with new line order.But throug my code I cannot generated it. The Code I use here is-
public class GeoCoordinates
{
public double Longitude { get; set; }
public double Latitude { get; set; }
}
public class POIData
{
public string Shorttext { get; set; }
public GeoCoordinates GeoCoordinates { get; set; }
public List<string> Images { get; set; }
}
Now My Class where I use this classes is
public GeoCoordinates GeosFromString(string path)
{
string[] lines = File.ReadAllLines(path);
GeoCoordinates gc = new GeoCoordinates();
gc.Latitude = Double.Parse(lines[0].Substring(4));
gc.Longitude = Double.Parse(lines[1].Substring(4));
return gc;
}
public void ToJsonForLocation(string name)
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "Text_ImageWithHash");
System.IO.Directory.CreateDirectory(folderName);
string fileName = name + ".json";
var path = Path.Combine(folderName, fileName);
var Jpeg_File = new DirectoryInfo(startPath + #"\Image\" + name).GetFiles("*.jpg");
POIData Poi=new POIData();
Poi.Shorttext = File.ReadAllText(startPath + #"\Short Text\" + name + ".txt");
Poi.GeoCoordinates=GeosFromString(startPath + #"\Latitude Longitude\" + name + ".txt");
Poi.Images=new List<string> { Jpeg_File[0].Name};
string json = JsonConvert.SerializeObject(Poi);
File.WriteAllText(path , json);
}

Try to replace this code:
string json = JsonConvert.SerializeObject(Poi);
With this:
string json = JsonConvert.SerializeObject(Poi, Formatting.Indented);

Related

Trying to properly set up query for match of 2 csv files got stuck

Here's an example of what the data looks like on each csv.
inventory.csv
ID, payment, Receipt#
90006, VISA, jk73kl_
90006, VISA, null
inventory.csv
INFO, VIEWS, DATE
9006_Produce_Banana_jk73kl__, 0, 10-13-20
9006_Produce_Banana, 0, 10-13-20
I am having trouble with my where, I need to search both forms and if there is a matching receipt number pull them out and combine the two rows.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
string[] ourDataSheet = System.IO.File.ReadAllLines(#"../../OurData.csv");
string[] theirDataSheet = System.IO.File.ReadAllLines(#"../../TheirData.csv");
string ourDataHeaders = ourDataSheet[0];
string theirDataHeaders = theirDataSheet[0];
IEnumerable<string> TrackingQuery =
from ourData in ourDataSheet
let ourDataFields = ourData.Split(',')
from theirData in theirDataSheet
let theirDataFields = theirData.Split(',')
where theirDataFields[0].EndsWith(ourDataFields[2])
select ourDataFields[0] + "," + ourDataFields[1] + "," + ourDataFields[2] + "," + theirDataFields[0] + "," + theirDataFields[0] + "," + theirDataFields[1] + "," + theirDataFields[2] + "," + theirDataFields[3];
OutPutResults(TrackingQuery);
Console.ReadKey();
}
static void OutPutResults(IEnumerable<string> query)
{
foreach(string item in query)
{
Console.WriteLine(item);
Console.Read();
}
}
}
}
First things first, I would recommend that you use a third-party package like CsvHelper and do something like the following
public class Sale
{
public int ID { get; set; }
public string Payment { get; set; }
[Name("Recipt#")]
public string Recipt { get; set; }
}
public class Inventory
{
public string INFO { get; set; }
public string VIEWS { get; set; }
public string DATE { get; set; }
}
IEnumerable<Sale> sales;
IEnumerable<Inventory> inventory;
using (var reader = new StreamReader(#"../../OurData.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
sales = csv.GetRecords<Sale>();
}
using (var reader = new StreamReader(#"../../TheirData.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
inventory = csv.GetRecords<Inventory>();
}
var results = sales.Where(s => inventory.Any(i => i.INFO.EndsWith(s.Recipt)));

breaking out all of the elements in a XML file C#

From another question I had, a answer almost got me there but I have hit a snag.
I need all of the deliveries from a descendant and they are all running together.
Current code I have tried (but it is only getting the first delivery section).
The problem that is being caused with the way I have tried below is that it does not handle the sections that have multiple sections.
I have a semi-working solution that uses data-tables but this is a much cleaner looking solution and I would really like to learn how to get it working like this.
var document = XDocument.Parse(xmlText);
var doc = XDocument.Parse(xmlText);
XNamespace ns0 = doc.Root.GetNamespaceOfPrefix("ns0");
XElement sender = doc.Descendants(ns0 + "SenderNameAndAddress").FirstOrDefault();
string[] senderAddress = sender.Descendants(ns0 + "Address").Elements().Select(x => (string)x).ToArray();
XElement recipientDeliveries = doc.Descendants(ns0 + "RecipientDeliveries").FirstOrDefault();
var results = recipientDeliveries.Elements(ns0 + "Recipient").Select(x => new
{
recipientCode = ((string)x.Descendants(ns0 + "RecipientCode").FirstOrDefault()),
name = (string)x.Descendants(ns0 + "Name").FirstOrDefault(),
address = x.Descendants(ns0 + "Address").Elements().Select(y => (string)y).ToArray(),
deliveries = x.Descendants(ns0 + "Deliveries").Elements().Select(y => (string)y).ToArray(),
deliveryID = (string)x.Descendants(ns0 + "DeliveryID").FirstOrDefault(),
deliveryType = (string)x.Descendants(ns0 + "DeliveryType").FirstOrDefault(),
deliveryRoute = (string)x.Descendants(ns0 + "DeliveryRoute").FirstOrDefault(),
toteID = (string)x.Descendants(ns0 + "ToteID").FirstOrDefault(),
nursingStation = (string)x.Descendants(ns0 + "NursingStation").FirstOrDefault()
}).ToList();
This is the xml sample
<?xml version="1.0" encoding="UTF-8"?>
<ns0:AdvancedShippingNotices xmlns:ns0="http://www.omnicare.com/schema/AdvancedShippingNotices.xsd">
<ns0:ASNID>4129114</ns0:ASNID>
<ns0:CourierID>4SAMEDAY</ns0:CourierID>
<ns0:SenderCode>598</ns0:SenderCode>
<ns0:SenderNameAndAddress>
<ns0:Name>Omnicare of San Diego</ns0:Name>
<ns0:Address>
<ns0:Line1>5601 Oberlin Drive, Suite 124</ns0:Line1>
<ns0:CityTownOrLocality>San Diego</ns0:CityTownOrLocality>
<ns0:StateOrProvince>CA</ns0:StateOrProvince>
<ns0:PostalCode>92121-3709</ns0:PostalCode>
</ns0:Address>
</ns0:SenderNameAndAddress>
<ns0:RecipientDeliveries>
<ns0:Recipient>
<ns0:RecipientCode>1019</ns0:RecipientCode>
<ns0:RecipientNameAndAddress>
<ns0:Name>VILLAGE SQUARE HEALTHCARE CTR</ns0:Name>
<ns0:Address>
<ns0:Line1>1586 W SAN MARCOS BLVD</ns0:Line1>
<ns0:CityTownOrLocality>SAN MARCOS</ns0:CityTownOrLocality>
<ns0:StateOrProvince>CA</ns0:StateOrProvince>
<ns0:PostalCode>92069</ns0:PostalCode>
</ns0:Address>
</ns0:RecipientNameAndAddress>
<ns0:Deliveries>
<ns0:Delivery>
<ns0:DeliveryID>8930798-5</ns0:DeliveryID>
<ns0:DeliveryType>ROUTE</ns0:DeliveryType>
<ns0:DeliveryRoute>R0130</ns0:DeliveryRoute>
<ns0:ToteID>S5-278</ns0:ToteID>
<ns0:NursingStation>2</ns0:NursingStation>
</ns0:Delivery>
<ns0:Delivery>
<ns0:DeliveryID>8934056-1</ns0:DeliveryID>
<ns0:DeliveryType>ROUTE</ns0:DeliveryType>
<ns0:DeliveryRoute>IV</ns0:DeliveryRoute>
<ns0:ToteID>B-132</ns0:ToteID>
<ns0:NursingStation>1</ns0:NursingStation>
</ns0:Delivery>
<ns0:Delivery>
<ns0:DeliveryID>8933908-1</ns0:DeliveryID>
<ns0:DeliveryType>CYCLE</ns0:DeliveryType>
<ns0:DeliveryRoute>CYCLE</ns0:DeliveryRoute>
<ns0:ToteID>B-132</ns0:ToteID>
<ns0:NursingStation>1</ns0:NursingStation>
</ns0:Delivery>
</ns0:Deliveries>
</ns0:Recipient>
<ns0:Recipient>
<ns0:RecipientCode>20366</ns0:RecipientCode>
<ns0:RecipientNameAndAddress>
<ns0:Name>OAKMONT OF ESCONDIDO HILLS</ns0:Name>
<ns0:Address>
<ns0:Line1>3012 BEAR VALLEY PKWY</ns0:Line1>
<ns0:CityTownOrLocality>ESCONDIDO</ns0:CityTownOrLocality>
<ns0:StateOrProvince>CA</ns0:StateOrProvince>
<ns0:PostalCode>92025</ns0:PostalCode>
</ns0:Address>
</ns0:RecipientNameAndAddress>
<ns0:Deliveries>
<ns0:Delivery>
<ns0:DeliveryID>8930798-4</ns0:DeliveryID>
<ns0:DeliveryType>ROUTE</ns0:DeliveryType>
<ns0:DeliveryRoute>R0130</ns0:DeliveryRoute>
<ns0:ToteID>F1-101</ns0:ToteID>
<ns0:NursingStation>AL</ns0:NursingStation>
</ns0:Delivery>
</ns0:Deliveries>
</ns0:Recipient>
</ns0:RecipientDeliveries>
</ns0:AdvancedShippingNotices>
Not sure if you actually use class models or not. But I did a little adjustment for for what's worth (It's will give you more flexibility with the data).
classes :
public class Recipient
{
public int RecipientCode { get; set; }
public RecipientInfo RecipientNameAndAddress { get; set; }
public IList<RecipientDelivery> Deliveries { get; set; }
}
public class RecipientInfo
{
public string Name { get; set; }
public RecipientAddress Address { get; set; }
}
public class RecipientAddress
{
public string Line1 { get; set; }
public string CityTownOrLocality { get; set; }
public string StateOrProvince { get; set; }
public string PostalCode { get; set; }
}
public class RecipientDelivery
{
public string DeliveryID { get; set; }
public string DeliveryType { get; set; }
public string DeliveryRoute { get; set; }
public string ToteID { get; set; }
public string NursingStation { get; set; }
}
then the work :
var doc = XDocument.Parse(file);
XNamespace ns0 = doc.Root.GetNamespaceOfPrefix("ns0");
XElement recipientDeliveries = doc.Descendants(ns0 + "RecipientDeliveries").FirstOrDefault();
var recipients = recipientDeliveries.Descendants(ns0 + "Recipient").ToList();
var RecipientList = new List<Recipient>();
foreach (var item in recipients)
{
var deliveries = item.Descendants(ns0 + "Deliveries").FirstOrDefault();
var deliveriesNodes = deliveries.Descendants(ns0 + "Delivery").ToList();
var recipientInfo = item.Descendants(ns0 + "RecipientNameAndAddress").FirstOrDefault();
var recipientAddress = recipientInfo.Descendants(ns0 + "Address").FirstOrDefault();
var deliverList = new List<RecipientDelivery>();
foreach (var del in deliveriesNodes)
{
var delivery = new RecipientDelivery()
{
DeliveryID = del.Element(ns0 + "DeliveryID").Value,
DeliveryType = del.Element(ns0 + "DeliveryType").Value,
DeliveryRoute = del.Element(ns0 + "DeliveryRoute").Value,
ToteID = del.Element(ns0 + "ToteID").Value,
NursingStation = del.Element(ns0 + "NursingStation").Value
};
deliverList.Add(delivery);
}
var recipient = new Recipient()
{
RecipientCode = Convert.ToInt32(item.Element(ns0 + "RecipientCode").Value),
RecipientNameAndAddress = new RecipientInfo()
{
Name = recipientInfo.Element(ns0 + "Name").Value.ToString(),
Address = new RecipientAddress()
{
Line1 = recipientAddress.Element(ns0 + "Line1").Value.ToString(),
CityTownOrLocality = recipientAddress.Element(ns0 + "CityTownOrLocality").Value.ToString(),
StateOrProvince = recipientAddress.Element(ns0 + "StateOrProvince").Value.ToString(),
PostalCode = recipientAddress.Element(ns0 + "PostalCode").Value.ToString()
},
},
Deliveries = deliverList
};
RecipientList.Add(recipient);
}
Then the whole Recipients will be in RecipientList, which you can use.
A small modification from previous results :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns0 = doc.Root.GetNamespaceOfPrefix("ns0");
XElement sender = doc.Descendants(ns0 + "SenderNameAndAddress").FirstOrDefault();
string[] senderAddress = sender.Descendants(ns0 + "Address").Elements().Select(x => (string)x).ToArray();
XElement recipientDeliveries = doc.Descendants(ns0 + "RecipientDeliveries").FirstOrDefault();
var results = recipientDeliveries.Elements(ns0 + "Recipient").Select(x => new
{
name = (string)x.Descendants(ns0 + "Name").FirstOrDefault(),
address = x.Descendants(ns0 + "Address").Elements().Select(y => (string)y).ToArray(),
deliveries = x.Descendants(ns0 + "Delivery").Select(y => new {
deliveryID = (string)y.Descendants(ns0 + "DeliveryID").FirstOrDefault(),
deliveryType = (string)y.Descendants(ns0 + "DeliveryType").FirstOrDefault(),
deliveryRoute = (string)y.Descendants(ns0 + "DeliveryRoute").FirstOrDefault(),
toteID = (string)y.Descendants(ns0 + "ToteID").FirstOrDefault(),
nursingStation = (string)y.Descendants(ns0 + "NursingStation").FirstOrDefault()
}).ToList()
}).ToList();
}
}
}

Nested JSON Array C#

I am trying to deserialize a JSON array that has an additional nested object.
Here is a sample C# code. It returns data until it gets to the second array. I know it needs a second foreach loop but I can't seem to get it to work. Any help would be greatly appreciated. Thank you.
string sJSON = #" [{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
JArray a = JArray.Parse(sJSON);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + "-- " + value);
}
}
You can use Newtonsoft.json library for serializing/deserializing the data, as per your requirement kindly follow below code :
First you need to create the class which will capture the data in specified format(as per your data requirement) :
public class RootObject
{
public int dateNumeric { get; set; }
public int hourOfDay { get; set; }
public int customerNumber { get; set; }
public List<Storedepartment> storedepartment { get; set; }
}
public class Storedepartment
{
public int department { get; set; }
public string descriptionOfDepartment { get; set; }
}
Now , for deserialising the Json data use below statement :
string sJSON = #" [{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
List<RootObject> Data = JsonConvert.DeserializeObject<List<RootObject>>(sJSON);
Once you get data in your list you can perform your required operation on list
Actually you might be able to properly parse your JSON string if you use the following approach.
public static void ProcessJObject(JProperty obj)
{
string name = obj.Name;
string value = "";
if (obj.Value.Type == JTokenType.Array)
{
Console.WriteLine("Array: " + name);
ProcessJArray((JArray)obj.Value);
}
else
{
value = (string)obj.Value;
Console.WriteLine(name + "-- " + value);
}
}
public static void ProcessJArray(JArray arr)
{
foreach (JObject o in arr.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
ProcessJObject(p);
}
}
}
static void Main(string[] args)
{
string sJSON = #" [{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
JArray a = JArray.Parse(sJSON);
ProcessJArray(a);
Console.Read();
}
So what have I done here. I simply divided the problem of parsing json in two smaller problems one that is solved by the ProcessJObject function (parsing and printing JProperty) and one that is solved by the ProcessJArray function (looping through the JArray and for each JProperty it contain passing it to ProcessJObject function). So now the parsing problem upto any point of nesting of JSON array is solved by the above approach.
Hope it helps.
static void JsonConvert()
{
string sJSON = #"[{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
var storeDetail = Newtonsoft.Json.JsonConvert.DeserializeObject<List<StoreDetail>>(sJSON);
//iterate your list here
}
public class StoreDetail
{
[JsonProperty("dateNumeric")]
public string DateNumeric { get; set; }
[JsonProperty("hourOfDay")]
public int HourOfDay { get; set; }
[JsonProperty("customerNumber")]
public int CustomerNumber { get; set; }
[JsonProperty("storedepartment")]
public List<StoreDepartment> StoreDepartment { get; set; }
}
public class StoreDepartment
{
[JsonProperty("department")]
public int Department { get; set; }
[JsonProperty("descriptionOfDepartment")]
public string DescriptionOfDepartment { get; set; }
}
string sJSON = #" [{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
object dJson = Newtonsoft.Json.JsonConvert.DeserializeObject<JArray>(sJSON);
Console.WriteLine(dJson.ToString());
JArray a = JArray.Parse(sJSON);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
if (p.First.Count() == 0)
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + "-- " + value);
}
else
{
string name = p.Name;
Console.WriteLine(name);
string subStr = p.Value.ToString();
JArray aSub = JArray.Parse(subStr);
foreach (JObject oSub in aSub.Children<JObject>())
{
foreach (JProperty pSub in oSub.Properties())
{
string nameSub = pSub.Name;
string valueSub = (string)pSub.Value;
Console.WriteLine("\t" + nameSub + "-- " + valueSub);
}
}
}
}
}
Console.ReadLine();

Using StreamWriter to write to different files in a Parallel.Foreach

I am attempting to write separate collections to seperate csv in a Parallel.Foreach loop. When I run this, I get the following error:
The process cannot access the file 'C:\temp\OCRProcess\2011\49\OCRProcess-2011-49.csv' because it is being used by another process.
When I look at all the worker processes, they are opening different files, none of them are using the same file location. From what I can tell, each thread (worker process) is not conflicting.
public void GenerateCSVFile(List<CSVFile> csvFiles)
{
Parallel.ForEach(csvFiles, (csvfile, state, index) =>
{
var fileLocation = _storageLocation + csvfile.Type + s + csvfile.Year + s + csvfile.Day + s + csvfile.Type + "-" +
csvfile.Year + "-" + csvfile.Day + ".csv";
if (!File.Exists(fileLocation))
{
File.Create(fileLocation);
}
using (var streamWriter = new StreamWriter(fileLocation))
{
foreach (var csvRecord in csvfile.CSVRecords)
{
streamWriter.WriteLine(csvRecord.Object_Id + "," + csvRecord.DocumentName + "," + csvRecord.BCI_DCN + "," + csvRecord.CreationDate);
}
}
});
}
Here is the CSVFile and CSVRecord classes just incase.
public sealed class CSVRecord
{
public String BCI_DCN { get; set; }
public String Object_Id { get; set; }
public String DocumentName { get; set; }
public String CreationDate { get; set; }
}
public sealed class CSVFile
{
public List<CSVRecord> CSVRecords { get; set; }
public String Year { get; set; }
public String Type { get; set; }
public String Day { get; set; }
public CSVFile()
{
CSVRecords = new List<CSVRecord>();
}
}
The issues is due to File.Create(fileLocation), which returns a FileStream and keeps the file open. When the StreamWriter attempted to open this, it was already open and caused the error.
To correct the problem, removed the following IF statement:
if (!File.Exists(fileLocation))
{
File.Create(fileLocation);
}
And updated the USING statement as followed. By adding the TRUE parameter, it allows StreamWriter to append to the file if it exists, otherwise create it.
using (var streamWriter = new StreamWriter(fileLocation, true))
{
foreach (var csvRecord in csvfile.CSVRecords)
{
streamWriter.WriteLine(csvRecord.Object_Id + "," + csvRecord.DocumentName + "," + csvRecord.BCI_DCN + "," + csvRecord.CreationDate);
}
}

taking data from a csv file, and putting it into an array

public class Earthquake
{
public double Magnitude { get; set; }
public string Location { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public double depth { get; set; }
public DateTime date { get; set; }
public string EventID { get; set; }
public string URL { get; set; }
public Earthquake()
: this(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty)
{ }
public Earthquake(string magna, string locate, string lat, string longi, string dept, string dat, string Event, string website)
{
Magnitude = Convert.ToDouble(magna);
Location = locate;
Latitude = Convert.ToDouble(lat);
Longitude = Convert.ToDouble(longi);
depth = Convert.ToDouble(dept);
date = Convert.ToDateTime(dat);
EventID = Event;
URL = website;
}
}
public void GetData()
{
string[] text = File.ReadAllLines(#"Earthquakes.csv");
Earthquake[] data = new Earthquake[1];
foreach (string line in text)
{
string[] myColumns = line.Split(',');
Earthquake[] earth = new Earthquake[myColumns[0], myColumns[1], myColumns[2], myColumns[3], myColumns[4], myColumns[5], myColumns[6], myColumns[7]];
data[i] = earth[i];
i++;
}
}
Ignore commented parts I have those under control. The problem I am having is getting the data from the csv file into the Earthquake Array. I am getting syntax errors, and I know why, it's because the data type isn't correct, but I honestly cannot figure out how to fix it.
Also if you notice I am trying to use bubble sort and since there is no definition for "compare" for double, what do I use instead?
If your reading from CSV file you probably have to remove white space from the split values.
Try adding .Trim() to your column variables
myColumns[0].Trim()
if your looking to sort yor array consider using System.Linq
eg:
var byMag = earthQuakes.OrderBy(e => e.Magnitude);
Looking at your code you posted, GetData() will not work.
Try returning a list or Enumerable
public IEnumerable<Earthquake> GetData(string filename)
{
string[] text = File.ReadAllLines(filename);
foreach (string line in text)
{
string[] myColumns = line.Split(',');
yield return new Earthquake(myColumns[0].Trim(), myColumns[1].Trim(), myColumns[2].Trim(), myColumns[3].Trim(), myColumns[4].Trim(), myColumns[5].Trim(), myColumns[6].Trim(), myColumns[7].Trim());
}
}
Usage:
var earthquakes = GetData(#"Earthquakes.csv");

Categories

Resources