Skip to content

Instantly share code, notes, and snippets.

@Babali42
Last active November 27, 2024 10:11
Show Gist options
  • Save Babali42/7a169bbe6c95b70f96d2961d84fb85e7 to your computer and use it in GitHub Desktop.
Save Babali42/7a169bbe6c95b70f96d2961d84fb85e7 to your computer and use it in GitHub Desktop.
Learn C# Linq Examples
//These code are easily convertible into linq version try them out
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitySC.PM.EME.Architecture.Test
{
[TestClass]
public class LinqDemoTests
{
List<Person> _people = new List<Person>()
{
new Person(54, "Henri"),
new Person(34, "Berenice"),
new Person(14, "Kevin"),
new Person(56, "Josiane"),
new Person(42, "Camille")
};
internal class Person
{
public int Age { get; set; }
public string FirstName { get; set; }
public Person(int age, string firstName)
{
Age = age;
FirstName = firstName;
}
internal void SayHello() => Console.WriteLine("Hello");
}
[TestMethod]
public void ForEach()
{
foreach (var person in _people)
{
person.SayHello();
}
Assert.IsTrue(true);
}
[TestMethod]
public void Filter()
{
var adults = new List<Person>();
foreach (var person in _people)
{
if (person.Age >= 18)
{
adults.Add(person);
}
}
Assert.AreEqual(4, adults.Count);
}
[TestMethod]
public void Projection()
{
var namesAndAges = new List<string>();
foreach (var person in _people)
{
namesAndAges.Add($"{person.FirstName} - {person.Age}");
}
var expectedNames = new List<string>() { "Henri - 54", "Berenice - 34", "Kevin - 14", "Josiane - 56", "Camille - 42" };
CollectionAssert.AreEquivalent(expectedNames, namesAndAges);
}
[TestMethod]
public void Reduction()
{
double average = 0;
foreach (var person in _people)
{
average += person.Age;
}
average /= _people.Count;
Assert.AreEqual(40, average);
// Same with Count()
}
[TestMethod]
public void Ordering()
{
int i = 0;
Person olderPerson = new Person(0,"");
do
{
if (_people[i].Age > olderPerson.Age)
olderPerson = _people[i];
i++;
} while (i < _people.Count);
var expectedOlderPersonName = "Josiane";
Assert.AreEqual(expectedOlderPersonName, olderPerson.FirstName);
}
[TestMethod]
public void Verify()
{
bool anyAdult = false;
foreach (var person in _people)
{
if (person.Age >= 18)
{
anyAdult = true;
}
}
Assert.IsTrue(anyAdult);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment