示例#1
0
     static void Main(string[] args)
     {
         var crimeData = new List<CrimeData>
         {
           using (StreamReader sr = new StreamReader("CrimeData.csv"))
         {
             string currentLine;
             while ((currentLine = sr.ReadLine()) != null)
             {
                 string[] values = currentLine.Split(',');
                 CrimeData crimeValues = new CrimeData();
                 crimeValues.Year = int.Parse(values[0]);
                 crimeValues.Population = int.Parse(values[1]);
                 crimeValues.ViolentCrime = int.Parse(values[2]);
                 crimeValues.Murder = int.Parse(values[3]);
                 crimeValues.Rape = int.Parse(values[4]);
                 crimeValues.Robbery = int.Parse(values[5]);
                 crimeValues.AggravatedAssault = int.Parse(values[6]);
                 crimeValues.PropertyCrime = int.Parse(values[7]);
                 crimeValues.Burglary = int.Parse(values[8]);
                 crimeValues.Theft = int.Parse(values[9]);
                 crimeValues.MotorVehicleTheft = int.Parse(values[10]);
             }
         }
     }
 };
示例#2
0
        private static bool ReadFile(string file)
        {
            Console.WriteLine($"Reading data from the file: {file}");
            try
            {
                int      fields         = 0;
                string[] crimeDataLines = File.ReadAllLines(file);

                for (int arrayIndex = 0; arrayIndex < crimeDataLines.Length; arrayIndex++)
                {
                    string   crimeDataLine = crimeDataLines[arrayIndex];
                    string[] data          = crimeDataLine.Split(",");

                    // Start
                    if (arrayIndex == 0)
                    {
                        fields = data.Length;
                    }
                    else
                    {
                        if (fields != data.Length)
                        {
                            Console.WriteLine($"Row {arrayIndex} contains {data.Length} values. It should contain {fields}");
                            return(false);
                        }
                        else
                        {
                            try
                            {
                                CrimeData crimeData = new CrimeData();
                                crimeData.Year               = Convert.ToInt32(data[0]);
                                crimeData.Population         = Convert.ToInt32(data[1]);
                                crimeData.Murders            = Convert.ToInt32(data[2]);
                                crimeData.Rapes              = Convert.ToInt32(data[3]);
                                crimeData.Robberies          = Convert.ToInt32(data[4]);
                                crimeData.ViolentCrimes      = Convert.ToInt32(data[5]);
                                crimeData.Thefts             = Convert.ToInt32(data[6]);
                                crimeData.MotorVehicleThefts = Convert.ToInt32(data[7]);
                                CrimeDataList.Add(crimeData);
                            }
                            catch (InvalidCastException)
                            {
                                Console.WriteLine($"Row {arrayIndex} contains an invalid value.");
                                return(false);
                            }
                        }
                    }
                }
                Console.WriteLine($"Crime data was read succesfully");
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error reading data from file");
                throw ex;
            }
        }
示例#3
0
 private static bool ReadData(string filePath)
 {
     try
     {
         int      columns        = 0;
         string[] crimeDataLines = File.ReadAllLines(filePath);
         for (int index = 0; index < crimeDataLines.Length; index++)
         {
             string   crimeDataLine = crimeDataLines[index];
             string[] data          = crimeDataLine.Split(',');
             if (index == 0) // Header
             {
                 columns = data.Length;
             }
             else
             {
                 if (columns != data.Length)
                 {
                     Console.WriteLine($"Row {index} contains {data.Length} values. It should contain {columns}.");
                     return(false);
                 }
                 else
                 {
                     try
                     {
                         CrimeData crimeData = new CrimeData();
                         crimeData.Year               = Convert.ToInt32(data[0]);
                         crimeData.Population         = Convert.ToInt32(data[1]);
                         crimeData.Murders            = Convert.ToInt32(data[2]);
                         crimeData.Rapes              = Convert.ToInt32(data[3]);
                         crimeData.Robberies          = Convert.ToInt32(data[4]);
                         crimeData.ViolentCrimes      = Convert.ToInt32(data[5]);
                         crimeData.Thefts             = Convert.ToInt32(data[6]);
                         crimeData.MotorVehicleThefts = Convert.ToInt32(data[7]);
                         CrimeDataList.Add(crimeData);
                     }
                     catch (InvalidCastException e)
                     {
                         Console.WriteLine($"Row {index} contains invalid value.");
                         return(false);
                     }
                 }
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error in reading data from csv file.");
         throw ex;
     }
 }
示例#4
0
        private static void WriteReport(string filePath)
        {
            try
            {
                if (CrimeDataList != null && CrimeDataList.Any())
                {
                    StringBuilder newString = new StringBuilder();

                    newString.Append("Crime Analyzer Report");
                    newString.Append(Environment.NewLine);
                    newString.Append(Environment.NewLine);

                    // 1 & 2
                    int minYear = CrimeDataList.Min(x => x.Year);
                    int maxYear = CrimeDataList.Max(x => x.Year);

                    int years = maxYear - minYear + 1;

                    newString.Append($"Period: {minYear}-{maxYear} ({years} years)");
                    newString.Append(Environment.NewLine);
                    newString.Append(Environment.NewLine);

                    // 3
                    var totalYears = from crimeData in CrimeDataList
                                     where crimeData.Murder < 15000
                                     select crimeData.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}");
                    newString.Append(Environment.NewLine);

                    // 4
                    var robYears = from crimeData in CrimeDataList
                                   where crimeData.Robbery > 500000
                                   select crimeData;

                    string robYearsStr = string.Empty;

                    for (int i = 0; i < robYears.Count(); i++)
                    {
                        CrimeData crimeData = robYears.ElementAt(i);

                        robYearsStr += $"{crimeData.Year} = {crimeData.Robbery}";

                        if (i < robYears.Count() - 1)
                        {
                            robYearsStr += ", ";
                        }
                    }

                    newString.Append($"Robberies per year > 500000: {robYearsStr}");
                    newString.Append(Environment.NewLine);

                    // 5
                    var violentCrime = from crimeData in CrimeDataList
                                       where crimeData.Year == 2010
                                       select crimeData;

                    CrimeData violentCrimeData = violentCrime.First();

                    double violentCrimePerCapita = (double)violentCrimeData.ViolentCrimes / (double)violentCrimeData.Population;

                    newString.Append($"Violent crime per capita rate (2010): {violentCrimePerCapita}");
                    newString.Append(Environment.NewLine);

                    // 6
                    double avgMurders = (float)CrimeDataList.Sum(x => x.Murder) / (float)CrimeDataList.Count;

                    newString.Append($"Average murder per year (all years): {avgMurders}");
                    newString.Append(Environment.NewLine);

                    // 7
                    int murder = CrimeDataList.Where(x => x.Year >= 1994 && x.Year <= 1997).Sum(y => y.Murder);

                    double avgMurder = (float)murder / 4;

                    newString.Append($"Average murder per year (1994-1997): {avgMurder}");
                    newString.Append(Environment.NewLine);

                    // 8
                    int murd = CrimeDataList.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}");
                    newString.Append(Environment.NewLine);

                    // 9
                    int minTheft = CrimeDataList.Where(x => x.Year >= 1999 && x.Year <= 2004).Min(x => x.Theft);

                    newString.Append($"Minimum thefts per year (1999-2004): {minTheft}");
                    newString.Append(Environment.NewLine);

                    // 10
                    int maxTheft = CrimeDataList.Where(x => x.Year >= 1999 && x.Year <= 2004).Max(x => x.Theft);

                    newString.Append($"Maximum thefts per year (1999-2004): {maxTheft}");
                    newString.Append(Environment.NewLine);

                    // 11
                    int maxVehicleTheft = CrimeDataList.OrderByDescending(x => x.MotorVehicleTheft).First().Year;

                    newString.Append($"Year of highest number of motor vehicle thefts: {maxVehicleTheft}");
                    newString.Append(Environment.NewLine);

                    using (var stream = new StreamWriter(filePath))
                    {
                        stream.Write(newString.ToString());
                    }

                    Console.WriteLine();
                    Console.WriteLine(newString.ToString());
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine($"No data to write.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in writing report file.");
                throw ex;
            }
        }
示例#5
0
        private static void CreateReport(string file)
        {
            try
            {
                if (CrimeDataList != null && CrimeDataList.Any())
                {
                    Console.WriteLine($"Calculating data and writing to report: {file}");
                    StringBuilder sb = new StringBuilder();
                    sb.Append("|||| Crime Analyzer Report ||||");
                    sb.Append("Environment.NewLine");

                    // Calc 1a
                    int minYear = CrimeDataList.Min(i => i.Year);
                    int maxYear = CrimeDataList.Max(i => i.Year);

                    // Calc 1b
                    int years = maxYear - minYear + 1;
                    sb.Append($"Period: {minYear} - {maxYear} ({years} years)");
                    sb.Append(Environment.NewLine);

                    // Calc 2
                    var mYears = from crimeData in CrimeDataList
                                 where crimeData.Murders < 15000
                                 select crimeData.Year;
                    string mYearsString = string.Empty;
                    for (int i = 0; i < mYears.Count(); i++)
                    {
                        mYearsString += mYears.ElementAt(i).ToString();
                        if (i < mYears.Count() - 1)
                        {
                            mYearsString += ",";
                        }
                    }
                    sb.Append($"Years murders per year < 15000: {mYearsString}");
                    sb.Append(Environment.NewLine);

                    // Calc 3
                    var robberyYears = from crimeData in CrimeDataList
                                       where crimeData.Robberies > 500000
                                       select crimeData;
                    string robberyYearsString = string.Empty;
                    for (int i = 0; i < robberyYears.Count(); i++)
                    {
                        CrimeData crimeData = robberyYears.ElementAt(i);
                        robberyYearsString += $"{crimeData.Year} = {crimeData.Robberies}";
                        if (i < robberyYears.Count() - 1)
                        {
                            robberyYearsString += ",";
                        }
                    }
                    sb.Append($"Robberies per year > 5000000: {robberyYearsString}");
                    sb.Append(Environment.NewLine);

                    // Calc 4
                    var vCrime = from crimeData in CrimeDataList
                                 where crimeData.Year == 2010
                                 select crimeData;
                    CrimeData vCrimeData            = vCrime.First();
                    double    violentCrimePerCapita = (double)vCrimeData.ViolentCrimes / (double)vCrimeData.Population;
                    sb.Append($"Violent crime per capita rate (2010): {violentCrimePerCapita}");
                    sb.Append(Environment.NewLine);

                    // Calc 5
                    double avgMurders = CrimeDataList.Sum(i => i.Murders) / CrimeDataList.Count;
                    sb.Append($"Average murder per year (all years): {avgMurders}");
                    sb.Append(Environment.NewLine);

                    //Calc 6
                    int murders1 = CrimeDataList
                                   .Where(x => x.Year >= 1994 && x.Year <= 1997)
                                   .Sum(y => y.Murders);
                    double avgMurders1 = murders1 / CrimeDataList.Count;
                    sb.Append($"Average murder per year (1994-1997): {avgMurders1}");
                    sb.Append(Environment.NewLine);

                    // Calc 7
                    int murders2 = CrimeDataList
                                   .Where(x => x.Year >= 2010 && x.Year <= 2014)
                                   .Sum(y => y.Murders);
                    double avgMurders2 = murders2 / CrimeDataList.Count;
                    sb.Append($"Average murder per year (2010-2014): {avgMurders2}");
                    sb.Append(Environment.NewLine);

                    // Calc 8
                    int minTheft = CrimeDataList
                                   .Where(x => x.Year >= 1999 && x.Year <= 2004)
                                   .Min(x => x.Thefts);
                    sb.Append($"Minimum thefts per year (1999-2004): {minTheft}");
                    sb.Append(Environment.NewLine);

                    // Calc 9
                    int maxTheft = CrimeDataList
                                   .Where(x => x.Year >= 1999 && x.Year <= 2004)
                                   .Max(x => x.Thefts);
                    sb.Append($"Maximum thefts per year (1999-2004): {maxTheft}");
                    sb.Append(Environment.NewLine);

                    // Calc 10
                    int yMaxVehicleTheft = CrimeDataList.OrderByDescending(x => x.MotorVehicleThefts).First().Year;
                    sb.Append($"Year of highest number of motor vehicle thefts: {yMaxVehicleTheft}");
                    sb.Append(Environment.NewLine);

                    using (var stream = new StreamWriter(file))
                    {
                        stream.Write(sb.ToString());
                    }

                    Console.WriteLine();
                    Console.WriteLine(sb.ToString());
                    Console.WriteLine();
                    Console.WriteLine($"Report successfully written to: {file}");
                }
                else
                {
                    Console.WriteLine($"No data to create report");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Sorry! There was an error writing report to file");
                throw ex;
            }
        }
示例#6
0
        static void Main(string[] args)
        {
            int count = 0;

            if (args.Length != 2)
            {
                Console.WriteLine("Please specify only the Crime Data file and the Crime Data Report file.");
                Console.ReadLine();
            }
            else
            {
                //Console.WriteLine("First Argument: " + args[0] + "Second Argument: " + args[1]);
                try
                {
                    using (var reader = new StreamReader(args[0]))
                    {
                        var crimeList = new List <CrimeData>();
                        while (!reader.EndOfStream)
                        {
                            var line   = reader.ReadLine();
                            var values = line.Split(',');

                            //Console.WriteLine("\nValues: " + values[0]);
                            if (count == 0)
                            {
                                count++;
                            }
                            else
                            {
                                var item = new CrimeData
                                {
                                    Year              = Int32.Parse(values[0]),
                                    Population        = Int32.Parse(values[1]),
                                    ViolentCrime      = Int32.Parse(values[2]),
                                    Murder            = Int32.Parse(values[3]),
                                    Rape              = Int32.Parse(values[4]),
                                    Robbery           = Int32.Parse(values[5]),
                                    AggravatedAssault = Int32.Parse(values[6]),
                                    PropertyCrime     = Int32.Parse(values[7]),
                                    Burglary          = Int32.Parse(values[8]),
                                    Theft             = Int32.Parse(values[9]),
                                    MotorVehicleTheft = Int32.Parse(values[10])
                                };
                                crimeList.Add(item);
                            }
                        }
                        Console.WriteLine("Please Work: " + crimeList[0].Year);
                        Console.WriteLine("Please Work: " + crimeList[1].Year);
                        Console.WriteLine("Please Work: " + crimeList[2].Year);
                        string header      = "Crime Analyzer Report\n\n";
                        string question1_2 = "Period: " + crimeList[0].Year + "-" + crimeList[crimeList.Count - 1].Year + " (" + crimeList.Count + " years)\n";
                        var    years       = from crimeStats in crimeList where crimeStats.Murder < 15000 select crimeStats.Year;
                        string question3   = "\nYears murders per year < 15000: ";
                        foreach (var year in years)
                        {
                            question3 += year + " ";
                        }
                        var    yearsAndRobberies = from crimeStats in crimeList where crimeStats.Robbery > 500000 select new { crimeStats.Year, crimeStats.Robbery };
                        string question4         = "\nRobberies per year > 500000: ";
                        foreach (var year in yearsAndRobberies)
                        {
                            question4 += year.Year + " = " + year.Robbery + " ";
                        }
                        var    violentCrimePerCapita = from crimeStats in crimeList where crimeStats.Year == 2010 select new { crimeStats.ViolentCrime, crimeStats.Population };
                        string question5             = "\nViolent crime per capita rate (2010): ";
                        foreach (var element in violentCrimePerCapita)
                        {
                            double vcpc = (double)element.ViolentCrime / element.Population;
                            Console.WriteLine(element.Population + "  " + element.ViolentCrime);
                            Console.WriteLine("vcpc: " + vcpc);
                            question5 += vcpc;
                        }
                        var    avgMurderAll     = crimeList.Average(x => x.Murder);
                        string question6        = "\nAverage murder per year (all years): " + avgMurderAll;
                        var    avgMurderQ7      = (from crimeStats in crimeList where crimeStats.Year <= 1997 select crimeStats.Murder).Average();
                        string question7        = "Average murder per year (1994–1997): " + avgMurderQ7;
                        var    avgMurderQ8      = (from crimeStats in crimeList where crimeStats.Year >= 2010 select crimeStats.Murder).Average();
                        string question8        = "Average murder per year (2010-2013): " + avgMurderQ8;
                        var    minThefts        = (from crimeStats in crimeList where crimeStats.Year >= 1999 && crimeStats.Year <= 2004 select crimeStats.Theft).Min();
                        string question9        = "Minimum thefts per year (1999–2004): " + minThefts;
                        var    maxThefts        = (from crimeStats in crimeList where crimeStats.Year >= 1999 && crimeStats.Year <= 2004 select crimeStats.Theft).Max();
                        string question10       = "Maximum thefts per year (1999–2004): " + maxThefts;
                        var    orderMotorThefts = from crimeStats in crimeList orderby crimeStats.MotorVehicleTheft descending select crimeStats.Year;
                        var    maxMotorThefts   = orderMotorThefts.FirstOrDefault();
                        string question11       = "Year of highest number of motor vehicle thefts: " + maxMotorThefts;
                        try
                        {
                            using (StreamWriter sw = new StreamWriter(args[1]))
                            {
                                sw.WriteLine(header);
                                sw.WriteLine(question1_2);
                                sw.WriteLine(question3);
                                sw.WriteLine(question4);
                                sw.WriteLine(question5);
                                sw.WriteLine(question6);
                                sw.WriteLine(question7);
                                sw.WriteLine(question8);
                                sw.WriteLine(question9);
                                sw.WriteLine(question10);
                                sw.WriteLine(question11);
                            }
                        }
                        catch (Exception Ex)
                        {
                            Console.WriteLine(Ex.ToString());
                            Environment.Exit(0);
                            Console.ReadLine();
                        }
                    }
                } catch (Exception Ex)
                {
                    Console.WriteLine(Ex.ToString());
                    Environment.Exit(0);
                    Console.ReadLine();
                }
            }
            //Console.ReadLine();
        }
示例#7
0
            private static void WriteReport(string filePath)
            {
                try
                {
                    if (CrimeDataList != null && CrimeDataList.Any())
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("Crime Analyzer Report");
                        sb.Append(Environment.NewLine);
                        // Period
                        int minYear = CrimeDataList.Min(x => x.Year);
                        int maxYear = CrimeDataList.Max(x => x.Year);
                        // Years
                        int years = maxYear - minYear + 1;
                        sb.Append($"Period: {minYear}-{maxYear} ({years} years)");
                        sb.Append(Environment.NewLine);

                        // Q2
                        var mYears = from crimeData in CrimeDataList
                                     where crimeData.Murders < 15000
                                     select crimeData.Year;

                        string mYearsStr = string.Empty;
                        for (int i = 0; i < mYears.Count(); i++)
                        {
                            mYearsStr += mYears.ElementAt(i).ToString();
                            // No comma after last value
                            if (i < mYears.Count() - 1)
                            {
                                mYearsStr += ", ";
                            }
                        }

                        sb.Append($"Years murders per year < 15000: {mYearsStr}");
                        sb.Append(Environment.NewLine);
                        // 3
                        var rYears = from crimeData in CrimeDataList
                                     where crimeData.Robberies > 500000
                                     select crimeData;

                        string rYearsStr = string.Empty;
                        for (int i = 0; i < rYears.Count(); i++)
                        {
                            CrimeData crimeData = rYears.ElementAt(i);
                            rYearsStr += $"{crimeData.Year} = {crimeData.Robberies}";
                            if (i < rYears.Count() - 1)
                            {
                                rYearsStr += ", ";
                            }
                        }

                        sb.Append($"Robberies per year > 500000: {rYearsStr}");
                        sb.Append(Environment.NewLine);

                        // 4
                        var vCrime = from crimeData in CrimeDataList
                                     where crimeData.Year == 2010
                                     select crimeData;
                        CrimeData vCrimeData      = vCrime.First();
                        double    vCrimePerCapita = (double)vCrimeData.ViolentCrimes / (double)vCrimeData.Population;
                        sb.Append($"Violent crime per capita rate (2010): {vCrimePerCapita}");
                        sb.Append(Environment.NewLine);

                        // 5
                        double avgMurders = CrimeDataList.Sum(x => x.Murders) / CrimeDataList.Count;
                        sb.Append($"Average murder per year (all years): {avgMurders}");
                        sb.Append(Environment.NewLine);

                        // 6
                        int murders1 = CrimeDataList
                                       .Where(x => x.Year >= 1994 && x.Year <= 1997)
                                       .Sum(y => y.Murders);
                        double avgMurders1 = murders1 / CrimeDataList.Count;
                        sb.Append($"Average murder per year (1994-1997): {avgMurders1}");
                        sb.Append(Environment.NewLine);

                        // 7
                        int murders2 = CrimeDataList
                                       .Where(x => x.Year >= 2010 && x.Year <= 2014)
                                       .Sum(y => y.Murders);
                        double avgMurders2 = murders2 / CrimeDataList.Count;
                        sb.Append($"Average murder per year (2010-2014): {avgMurders2}");
                        sb.Append(Environment.NewLine);

                        // 8
                        int minTheft = CrimeDataList
                                       .Where(x => x.Year >= 1999 && x.Year <= 2004)
                                       .Min(x => x.Thefts);
                        sb.Append($"Minimum thefts per year (1999-2004): {minTheft}");
                        sb.Append(Environment.NewLine);

                        // 9
                        int maxTheft = CrimeDataList
                                       .Where(x => x.Year >= 1999 && x.Year <= 2004)
                                       .Max(x => x.Thefts);
                        sb.Append($"Maximum thefts per year (1999-2004): {maxTheft}");
                        sb.Append(Environment.NewLine);

                        // 10
                        int yMaxVehicleTheft = CrimeDataList.OrderByDescending(x => x.MotorVehicleThefts).First().Year;
                        sb.Append($"Year of highest number of motor vehicle thefts: {yMaxVehicleTheft}");
                        sb.Append(Environment.NewLine);
                        using (var stream = new StreamWriter(filePath))
                        {
                            stream.Write(sb.ToString());
                        }
                        Console.WriteLine();
                        Console.WriteLine(sb.ToString());
                    }
                    else
                    {
                        Console.WriteLine($"No data to write.");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error in writing report file.");
                    throw ex;
                }
            }