public void Read(string file) { Console.WriteLine("Reading data from file : {file}"); try { string[] lines = File.ReadAllLines(file); for (int index = 0; index < lines.Length; index++) { string line = lines[index]; string[] values = line.Split(','); CrimeStats crimeStat = new CrimeStats(); crimeStat.Year = Int32.Parse(values[0]); crimeStat.Population = Int32.Parse(values[1]); crimeStat.Murders = Int32.Parse(values[2]); crimeStat.Rapes = Int32.Parse(values[3]); crimeStat.Robberies = Int32.Parse(values[4]); crimeStat.ViolentCrimes = Int32.Parse(values[5]); crimeStat.Thefts = Int32.Parse(values[6]); crimeStat.MotorVehicleThefts = Int32.Parse(values[7]); crimeStatsList.Add(crimeStat); } Console.WriteLine("Reading completed."); } catch (Exception ex) { Console.WriteLine("Unable to read CSV file. Please try again."); throw ex; } }
static void Main(string[] args) { string file; string report; Console.WriteLine("Please enter in a file path for your csv file"); file = GetValidDocument(); Console.WriteLine("Now enter in a file path for the report file"); report = Console.ReadLine(); if (report == null) { Console.WriteLine("Enter in a report filename"); } CrimeStats crimeStats = new CrimeStats(); if (File.Exists(file)) { crimeStats.Read(file); var fileReader = File.Create(report); fileReader.Close(); crimeStats.linqWriting(report); } else { Console.WriteLine("Please enter in a CSV file that can be used with data that's not: {file}"); } }
public static List <CrimeStats> Load(string csvDataFilePath) { List <CrimeStats> crimeStatsList = new List <CrimeStats>(); try { using (var reader = new StreamReader(csvDataFilePath)) { int lineNum = 0; while (!reader.EndOfStream) { var info = reader.ReadLine(); lineNum++; if (lineNum == 1) { continue; } var values = info.Split(','); if (values.Length != ItemsInRow) { throw new Exception($"Row {lineNum} contains {values.Length} values. It should contain {ItemsInRow}."); } try { int year = int.Parse(values[0]); int population = int.Parse(values[1]); int violentCrime = int.Parse(values[2]); int murder = int.Parse(values[3]); int rape = int.Parse(values[4]); int robbery = int.Parse(values[5]); int aggravatedAssault = int.Parse(values[6]); int propertyCrime = int.Parse(values[7]); int burglary = int.Parse(values[8]); int theft = int.Parse(values[9]); int motorVehicleTheft = int.Parse(values[10]); CrimeStats crimeStats = new CrimeStats(year, population, violentCrime, murder, rape, robbery, aggravatedAssault, propertyCrime, burglary, theft, motorVehicleTheft); crimeStatsList.Add(crimeStats); } catch (FormatException e) { throw new Exception($"Row {lineNum} contains invalid data. ({e.Message})"); } } } } catch (Exception e) { throw new Exception($"Unable to open {csvDataFilePath} ({e.Message})."); } return(crimeStatsList); }
private static bool ReadStats(string filePath) { try { int column = 0; string[] crimeStatsLines = File.ReadAllLines(filePath); for (int index = 0; index < crimeStatsLines.Length; index++) { string crimeStatsLine = crimeStatsLines[index]; string[] data = crimeStatsLine.Split(','); if (column != data.Length) { throw new Exception($"Invalid"); } try { int Year = Int32.Parse(data[0]); int Population = Int32.Parse(data[1]); int ViolentCrimes = Int32.Parse(data[2]); int Murder = Int32.Parse(data[3]); int Rape = Int32.Parse(data[4]); int Robbery = Int32.Parse(data[5]); int AggravatedAssault = Int32.Parse(data[6]); int PropertyCrime = Int32.Parse(data[7]); int Burglary = Int32.Parse(data[8]); int Theft = Int32.Parse(data[9]); int MotorVehicleTheft = Int32.Parse(data[10]); CrimeStats crimeStats = new CrimeStats(Year, Population, ViolentCrimes, Murder, Rape, Robbery, AggravatedAssault, PropertyCrime, Burglary, Theft, MotorVehicleTheft); CrimeStatsList.Add(crimeStats); } catch (InvalidCastException) { Console.WriteLine($"There is an invalid value."); return(false); } } } catch (Exception ex) { Console.WriteLine("An Error Occurred."); throw ex; } return(true); }
private static List <CrimeStats> ParseCrimeStatsList(IEnumerable <string> readLines, Dictionary <string, int> headerIndexes) { List <CrimeStats> crimeStatsList = new List <CrimeStats>(); for (int i = 1; i < readLines.Count(); i++) { string readLine = readLines.ElementAt(i); try { CrimeStats c = CrimeStats.BuildFromReadData(headerIndexes, readLine); crimeStatsList.Add(c); } catch (Exception e) { Console.WriteLine("Failed to build record from line {0} from input file.", i); Console.WriteLine(e.Message); Environment.Exit(1); } } return(crimeStatsList); }
public void linqWriting(string filePath) { try { if (crimeStatsList != null && crimeStatsList.Any()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Crime Analyzer Report\n"); double minYear = crimeStatsList.Min(n => n.Year); double maxYear = crimeStatsList.Max(n => n.Year); double yearRange = maxYear - minYear + 1; stringBuilder.Append("Period: {minYear}-{maxYear} ({yearRange} years)\n"); var numberOfYears = from crimeStat in crimeStatsList select crimeStat.Year; stringBuilder.Append("Years murders per year: {mYearsStr}\n"); var yearsWhereMurdersWereLessThan15000 = from crimeStat in crimeStatsList where crimeStat.Murders < 15000 select crimeStat.Year; stringBuilder.Append("Years murders per year < 15000: {yearsWhereMurdersWereLessThan15000}\n"); var aWholeLotOfRobberies = from crimeStat in crimeStatsList where crimeStat.Robberies > 500000 select crimeStat; string robberiesYears = null; for (int i = 0; i < aWholeLotOfRobberies.Count(); i++) { CrimeStats crimeStats = aWholeLotOfRobberies.ElementAt(i); robberiesYears += "{crimeStats.Year} = {crimeStats.Robberies}"; if (i < aWholeLotOfRobberies.Count() - 1) { robberiesYears += ", "; } } stringBuilder.Append("Robberies per year > 500000: {robberiesYears}\n"); var violentCrime = from crimeStats in crimeStatsList where crimeStats.Year == 2010 select crimeStats; CrimeStats violentCrimeData = violentCrime.First(); double violentCrimePerCapita = (double)violentCrimeData.ViolentCrimes / (double)violentCrimeData.Population; stringBuilder.Append("Violent crime per capita rate (2010): {violentCrimePerCapita}\n"); double avgMurders = crimeStatsList.Sum(n => n.Murders) / crimeStatsList.Count; stringBuilder.Append("Average murder per year (all years): {avgMurders}\n"); double murders1 = crimeStatsList .Where(n => n.Year >= 1994 && n.Year <= 1997) .Sum(y => y.Murders); double avgMurders1 = murders1 / crimeStatsList.Count; stringBuilder.Append("Average murder per year (1994-1997): {avgMurders1}\n"); double murders2 = crimeStatsList .Where(n => n.Year >= 2010 && n.Year <= 2014) .Sum(y => y.Murders); double avgMurders2 = murders2 / crimeStatsList.Count; stringBuilder.Append("Average murder per year (2010-2014): {avgMurders2}\n"); double minTheft = crimeStatsList .Where(n => n.Year >= 1999 && n.Year <= 2004) .Min(n => n.Thefts); stringBuilder.Append("Minimum thefts per year (1999-2004): {minTheft}\n"); double maxTheft = crimeStatsList .Where(n => n.Year >= 1999 && n.Year <= 2004) .Max(n => n.Thefts); stringBuilder.Append("Maximum thefts per year (1999-2004): {maxTheft}\n"); double maxVehicleTheft = crimeStatsList.OrderByDescending(n => n.MotorVehicleThefts).First().Year; stringBuilder.Append("Year of highest number of motor vehicle thefts: {maxVehicleTheft}\n"); using (var stream = new StreamWriter(filePath)) { stream.Write(stringBuilder); } Console.WriteLine("Written report successfully."); } } catch (Exception e) { Console.WriteLine("Error in writing report file."); throw e; } }
static void Main(string[] args) { Console.WriteLine("Welcom to the Crime Analyzer"); Console.WriteLine("\n"); Console.WriteLine("This program will analyze crime statistics."); if (args.Length >= 2) { string reportFile = args[1]; var csvFile = args[0]; try { using (var sr = new StreamReader(csvFile)) { List <string> years = new List <string>(); List <string> populations = new List <string>(); List <string> violentCrimes = new List <string>(); List <string> murders = new List <string>(); List <string> rapes = new List <string>(); List <string> robberies = new List <string>(); List <string> aggAssaults = new List <string>(); List <string> propertyCrimes = new List <string>(); List <string> burglaries = new List <string>(); List <string> thefts = new List <string>(); List <string> mvts = new List <string>(); while (!sr.EndOfStream) { var line = sr.ReadLine(); var values = line.Split(','); int year = Int32.Parse(values[0]); int population = Int32.Parse(values[1]); int violentCrime = Int32.Parse(values[2]); int murder = Int32.Parse(values[3]); int rape = Int32.Parse(values[4]); int robbery = Int32.Parse(values[5]); int aggravatedAssault = Int32.Parse(values[6]); int propertyCrime = Int32.Parse(values[7]); int burglary = Int32.Parse(values[8]); int theft = Int32.Parse(values[9]); int mvt = Int32.Parse(values[10]); CrimeStats crimeStats = new CrimeStats(year, population, violentCrime, murder, rape, robbery, aggravatedAssault, propertyCrime, burglary, theft, mvt); IEnumerable <string> yearQuery = from year1 in years where murder < 15000 select year1; foreach (string year1 in yearQuery) { Console.WriteLine("year" + ""); } } //First Question string minYear = years[1]; string maxYear = years.Last() : StringBuilder newString = new StringBuilder(); newString.Append("Your Crime Analyzer Report"); newString.Append(Environment.NewLine); newString.Append(Environment.NewLine); newString.Append("Time Period: " + minYear + "-" + maxYear); using (var stream = new StreamWriter(reportFile)) { stream.Write(newString.ToString()); Console.WriteLine(newString.ToString()); } } } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } } else { Console.WriteLine("You must give 2 arguments: .csv file and report file."); } }
internal static void Add(CrimeStats CrimeStats) { throw new NotImplementedException(); }
public static void Main(string[] args) { string line; try { List <CrimeStats> crimeStatsList = new List <CrimeStats>(); //Console.WriteLine("Enter the File name:"); /// string filename = Console.ReadLine(); string filename = args[0]; // csv file //Console.WriteLine("Enter the report filename:"); // string report = Console.ReadLine(); string report = args[1]; // report file StreamWriter sw = new StreamWriter(report); StreamReader sr = new StreamReader(filename); /// read first line line = sr.ReadLine(); // Second line where data starts line = sr.ReadLine(); while (line != null) { string[] columns = line.Split(','); // columns[0] == year columns[1] == population columns[2] == Violent Crime int year = Convert.ToInt32(columns[0]); int population = Convert.ToInt32(columns[1]); int violentCrime = Convert.ToInt32(columns[2]); int murder = Convert.ToInt32(columns[3]); int rape = Convert.ToInt32(columns[4]); int robbery = Convert.ToInt32(columns[5]); int aggravatedAssault = Convert.ToInt32(columns[6]); int propertyCrime = Convert.ToInt32(columns[7]); int burglary = Convert.ToInt32(columns[8]); int theft = Convert.ToInt32(columns[9]); int motorVehicleTheft = Convert.ToInt32(columns[10]); // Read next line line = sr.ReadLine(); CrimeStats crimeStats = new CrimeStats(year, population, violentCrime, murder, rape, robbery, aggravatedAssault, propertyCrime, burglary, theft, motorVehicleTheft); crimeStatsList.Add(crimeStats); } // What is the range of years included in the data? IEnumerable <int> q1 = from crimeStats in crimeStatsList where crimeStats.year >= 1994 && crimeStats.year < 2014 select crimeStats.year; Console.WriteLine($"Period {q1.Min()} - {q1.Max()} ({q1.Max() - q1.Min()} years)"); sw.WriteLine($"Period {q1.Min()} - {q1.Max()} ({q1.Max() - q1.Min()} years)"); // How many years of data are included? IEnumerable <int> q2 = from crimeStats in crimeStatsList select crimeStats.year; Console.WriteLine($"Year count {q2.Count()}"); sw.WriteLine($"Year count {q2.Count()}"); // What years is the number of murders per year less than 15000? IEnumerable <int> q3 = from crimeStats in crimeStatsList where crimeStats.murder < 15000 select crimeStats.year; Console.Write($"Years murders per year< 15000: "); sw.Write($"Years murders per year< 15000: "); foreach (int x in q3) { Console.Write($"{x}, "); sw.Write($"{x}, "); } Console.WriteLine("\n"); sw.WriteLine("\n"); // What are the years and associated robberies per year for years where the number of robberies is greater than 500000 ? IEnumerable <int> q4 = from crimeStats in crimeStatsList where crimeStats.robbery > 500000 select crimeStats.year; Console.Write("Robberies per year > 500000 "); sw.Write("Robberies per year > 500000 "); foreach (int x in q4) { Console.Write($"{x}, "); sw.Write($"{x}, "); } Console.WriteLine("\n"); sw.WriteLine("\n"); // What is the violent crime per capita rate for 2010? Per capita rate is the number of violent crimes in a year divided by the size of the population that year. IEnumerable <double> q5 = from crimeStats in crimeStatsList where crimeStats.year == 2010 select crimeStats.violentCrime / (double)crimeStats.population; Console.Write("Violent crime per capita rate(2010): "); sw.Write("Violent crime per capita rate(2010): "); foreach (double x in q5) { Console.Write(x); sw.Write(x); } Console.WriteLine("\n"); sw.WriteLine("\n"); // What is the average number of murders per year across all years? IEnumerable <int> q6 = from crimeStats in crimeStatsList select crimeStats.murder; double avg_murder = q6.Average(); Console.WriteLine($"Average murder per year (all years): {avg_murder}"); sw.WriteLine($"Average murder per year (all years): {avg_murder}"); // What is the average number of murders per year for 1994 to 1997? IEnumerable <int> q7 = from crimeStats in crimeStatsList where crimeStats.year >= 1994 && crimeStats.year <= 1997 select crimeStats.murder; double avg_murder2 = q7.Average(); Console.WriteLine($"Average murder per year (1994-1997) {avg_murder2}"); sw.WriteLine($"Average murder per year (1994-1997) {avg_murder2}"); // What is the average number of murders per year for 2010 to 2013? IEnumerable <int> q8 = from crimeStats in crimeStatsList where crimeStats.year >= 2010 && crimeStats.year <= 2013 select crimeStats.murder; double avg_murder3 = q8.Average(); Console.WriteLine($"Average murder per year (2010-2013) {avg_murder3}"); sw.WriteLine($"Average murder per year (2010-2013) {avg_murder3}"); // What is the minimum number of thefts per year for 1999 to 2004? IEnumerable <int> q9 = from crimeStats in crimeStatsList where crimeStats.year >= 1999 && crimeStats.year <= 2004 select crimeStats.theft; Console.WriteLine($"Minimum thefts per year (1999-2004): {q9.Min()}"); sw.WriteLine($"Minimum thefts per year (1999-2004): {q9.Min()}"); // QUESTION 10 What is the maximum number of thefts per year for 1999 to 2004 ? Console.WriteLine($"Maximum thefts per year (1999-2004): {q9.Max()}"); sw.WriteLine($"Maximum thefts per year (1999-2004): {q9.Max()}"); // What year had the highest number of motor vehicle thefts? IEnumerable <int> q11 = from crimeStats in crimeStatsList where crimeStats.motorVehicleTheft > 1 select crimeStats.motorVehicleTheft; int highest_murder = q11.Max(); // get year IEnumerable <int> q11_1 = from crimeStats in crimeStatsList where crimeStats.motorVehicleTheft == highest_murder select crimeStats.year; foreach (int x in q11_1) { sw.WriteLine($"Year of highest number of motor vehicle thefts {x}"); break; } sr.Close(); sw.Close(); } catch (Exception e) { Console.WriteLine("Exception:" + e.Message); } finally { Console.WriteLine("final block"); } }
static void GenerateCrimeReport(List <CrimeStats> CrimeStatsList, string filePath) { if (CrimeStatsList.Count == 0) { throw new CrimeReportEmptyDataException("Data provided for the Crime Report is empty. Please check your CSV file."); } StreamWriter sw = null; try { sw = new StreamWriter(filePath); sw.WriteLine("+= Crime Analyzer Report =+\n"); IEnumerable <int> years = from CrimeStats in CrimeStatsList select CrimeStats.Year; int start = years.Min(); int end = years.Max(); int span = end - start + 1; sw.WriteLine("Period: {0}-{1} ({2} year{3})\n", start, end, span, span > 1 ? "s" : ""); string csv = ""; int index = 0; IEnumerable <int> murderYears = from CrimeStats in CrimeStatsList where CrimeStats.Murder < 15000 select CrimeStats.Year; foreach (int year in murderYears) { csv += string.Format("{0}{1}", year, index < (murderYears.Count() - 1) ? ", " : ""); ++index; } sw.WriteLine("Years murders per year < 15000: {0}", csv); csv = ""; index = 0; IEnumerable <CrimeStats> robberyStats = from CrimeStats in CrimeStatsList where CrimeStats.Robbery > 500000 select CrimeStats; foreach (CrimeStats stats in robberyStats) { csv += string.Format("{0} = {1}{2}", stats.Year, stats.Robbery, index < (robberyStats.Count() - 1) ? ", " : ""); ++index; } sw.WriteLine("Robberies per year > 500000: {0}", csv); CrimeStats cpcYear = (from CrimeStats in CrimeStatsList where CrimeStats.Year == 2010 select CrimeStats).FirstOrDefault(); string cpcText = cpcYear == null ? "No data to calculate crime per capita in 2010" : ((double)cpcYear.ViolentCrime / cpcYear.Population).ToString(); sw.WriteLine("Violent crime per capita rate (2010): {0}", cpcText); double averageMurders = (from CrimeStats in CrimeStatsList select CrimeStats.Murder).Average(); sw.WriteLine("Average murders per year (all years): {0}", averageMurders); averageMurders = (from CrimeStats in CrimeStatsList where (CrimeStats.Year >= 1994 && CrimeStats.Year <= 1997) select CrimeStats.Murder).Average(); sw.WriteLine("Average murders per year (1994-1997): {0}", averageMurders); averageMurders = (from CrimeStats in CrimeStatsList where (CrimeStats.Year >= 2010 && CrimeStats.Year <= 2014) select CrimeStats.Murder).Average(); sw.WriteLine("Average murders per year (2010-2014): {0}", averageMurders); IEnumerable <int> thefts = (from CrimeStats in CrimeStatsList where (CrimeStats.Year >= 1999 && CrimeStats.Year <= 2004) select CrimeStats.Theft); sw.WriteLine("Minimum Therfts per year (1999-2004): {0}", thefts.Min()); sw.WriteLine("Maximum Therfts per year (1999-2004): {0}", thefts.Max()); int maxMotorTheftsYear = (from CrimeStats in CrimeStatsList let maxMotorTheft = CrimeStatsList.Max(stats => stats.MotorVehicleTheft) where CrimeStats.MotorVehicleTheft == maxMotorTheft select CrimeStats.Year).FirstOrDefault(); sw.WriteLine("Year with the highest number of Motor Vehicle thefts: {0}", maxMotorTheftsYear); } catch (Exception e) { if (e is UnauthorizedAccessException || e is ArgumentException || e is DirectoryNotFoundException || e is PathTooLongException || e is IOException) { throw new CrimeReportFileWriteException(string.Format("File at \"{0}\" is incorrect.\nPath either does not exist or is formatted incorrectly.\nPlease try again.", filePath)); } else { throw e; } } finally { if (sw != null) { sw.Close(); } } }
private static void WriteReport(string filePath) { try { if (CrimeStatsList != null && CrimeStatsList.Any()) { StringBuilder newString = new StringBuilder(); newString.Append("Crime Analyzer Report\n\n"); int minYear = CrimeStatsList.Min(x => x.Year); int maxYear = CrimeStatsList.Max(x => x.Year); int years = maxYear - minYear + 1; newString.Append($"Period: { minYear}-{ maxYear} ({ years} years\n\n"); var totalYears = from crimeStats in CrimeStatsList where crimeStats.Murder < 15000 select crimeStats.Year; string totalYearsStr = string.Empty; for (int i = 0; i < totalYears.Count(); i++) { totalYearsStr += totalYears.ElementAt(i).ToString(); if (i < totalYears.Count() - 1) { totalYearsStr += ", "; } } newString.Append($"Years murders per year < 15000: { totalYearsStr}\n"); var robYears = from crimeStats in CrimeStatsList where crimeStats.Robbery > 500000 select crimeStats; string robYearsStr = string.Empty; for (int i = 0; i < robYears.Count(); i++) { CrimeStats crimeStats = robYears.ElementAt(i); robYearsStr += $"{ crimeStats.Year} = { crimeStats.Robbery}"; if (i < robYears.Count() - 1) { robYearsStr += ", "; } } newString.Append($"Robberies per year > 500000: { robYearsStr}\n"); var violentCrime = from crimeStats in CrimeStatsList where crimeStats.Year == 2010 select crimeStats; CrimeStats violentCrimeStats = violentCrime.First(); double violentCrimePerCapita = (double)violentCrimeStats.ViolentCrimes / (double)violentCrimeStats.Population; double avgMurders = (float)CrimeStatsList.Sum(x => x.Murder) / (float)CrimeStatsList.Count; newString.Append($"Average murder per year (all years): { avgMurders}\n"); int murd = CrimeStatsList.Where(x => x.Year >= 2010 && x.Year <= 2014).Sum(y => y.Murder); double avgMurd = (float)murd / 5; newString.Append($"Average murder per year (2010-2014): { avgMurd}\n"); int minTheft = CrimeStatsList.Where(x => x.Year >= 1999 && x.Year <= 2004).Min(x => x.Theft); newString.Append($"Minimum thefts per year (1999-2004): { minTheft}\n"); int maxTheft = CrimeStatsList.Where(x => x.Year >= 1999 && x.Year <= 2004).Max(x => x.Theft); newString.Append($"Maximum thefts per year (1999-2004): { maxTheft}\n"); int maxVehicleTheft = CrimeStatsList.OrderByDescending(x => x.MotorVehicleTheft).First().Year; newString.Append($"Year of highest number of motor vehicle thefts: { maxVehicleTheft}\n"); using (var stream = new StreamWriter(filePath)) { stream.Write(newString.ToString()); } Console.WriteLine(); Console.WriteLine(newString.ToString()); Console.WriteLine(); } else { Console.WriteLine($"No Data."); } } catch (Exception ex) { Console.WriteLine("Error."); throw ex; } }