C# – LINQ, ForEach, Classes, Override
Some 2.5 years ago I have first written an article for LINQ, when I was learning it. Now, I was watching at some videos about algorithms and I realized I have not used LINQ in quite a while and I have forgotten how it works. Thus, I have decided to make my Sunday evening a little more productive and to write a small program, that can remind me of what I was the LINQ usage 🙂
Thus, lets imagine that we have 6 companies and each one has a name, CEO, profit and country. In order to mimic this idea, I have built up the class Company.cs:
namespace linq_test
{
class Company
{
private string _companyName;
private string _companyCEO;
private int _companyProfit;
private string _companyCountry;
public Company(string name, string ceo = "No CEO", int profit = 0, string country = "Bulgaria")
{
_companyName = name;
_companyCEO = ceo;
_companyProfit = profit;
_companyCountry = country;
}
public string name
{
get { return _companyName; }
}
public int profit
{
get {return _companyProfit;}
}
public string country
{
get {return _companyCountry;}
}
public string ceo
{
get
{
return _companyCEO;
}
set
{
_companyCEO = value;
}
}
public override string ToString()
{
return string.Format("This company is named {0}. The CEO is {1}. The profit is {2}. It is located in {3}.",
this.name, this.ceo, this.profit, this.country);
}
}
}
As you see above, I have overridden the ToString method with my own, which I would be using later. Something else worth noting, is that I have optional parameters in the builder and I have setter only for the CompanyCEO name. The rest is standard.
In my other class, called LinqApp.cs I define 6 objects of type Company. Then I use LINQ to build up first the Bulgarian companies only and then only the once with profit above 0. This is what I get:

This is the code from the LinqApp.cs class:
using System;
using System.Collections.Generic;
using System.Linq;
namespace linq_test
{
class LinqApp
{
static void Main()
{
Company c1 = new Company("VitoshAcademy", "Vitosh", 10, "Bulgaria");
Company c2 = new Company("VitoshAcademy2", "Vitosh", 12, "Russia");
Company c3 = new Company("SomeBadCompany", "Vitosh", 14, "Germany");
Company c4 = new Company("SomeBadCompany2", "Creepy", 16, "Germany");
Company c5 = new Company("SomeBadCompany3", "Creepy");
Company c6 = new Company("SomeBadCompany4", "Vitosh");
List companies = new List { c1, c2, c3, c4, c5, c6 };
var bulgarian_companies = from my_company in companies
where my_company.country == "Bulgaria"
select my_company;
Console.WriteLine("Bulgarian companies only:");
foreach (var company in bulgarian_companies)
{
Console.WriteLine(company.ToString());
}
Console.WriteLine("\nCompanies with a positive profit :");
var companies_with_profit = from my_company in companies
where my_company.profit > 0
select my_company;
foreach (var company in companies_with_profit)
{
Console.WriteLine(company.ToString());
}
}
}
}
If you want to see the files in GitHub, here they are! Enjoy! 😀