Skip to content

Instantly share code, notes, and snippets.

@dhcgn
Created July 20, 2023 12:01
Show Gist options
  • Save dhcgn/49d63d28f2723a4edbfc6bfa5efb576e to your computer and use it in GitHub Desktop.
Save dhcgn/49d63d28f2723a4edbfc6bfa5efb576e to your computer and use it in GitHub Desktop.
Teach Linq
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
var apples = new List<Apple>(){
new Apple(){Color = "Red", Weight = 100},
new Apple(){Color = "Green", Weight = 200},
new Apple(){Color = "Yellow", Weight = 300},
new Apple(){Color = "Red", Weight= 400},
new Apple(){Color = "Blue", Weight = 500},
};
var redApples = apples.Where(a => a.Color == "Red");
System.Console.WriteLine($"There are {redApples.Count()} red apples");
var blueApples = FilterFarbeApfel(apples, "Blue");
System.Console.WriteLine($"There are {blueApples.Count()} blue apples");
var applesWith300 = FilterWeightApfel(apples, 300);
System.Console.WriteLine($"There are {blueApples.Count()} apples with 300 weight");
var redApple = apples.FirstOrDefault(a => a.Color == "Red");
System.Console.WriteLine($"There is {redApple?.Color} apple");
bool IsAppleOver300(Apple apple){
return apple.Weight > 300;
}
var applesOver300 = FilterApfel(apples, IsAppleOver300);
applesOver300 = FilterApfel(apples, apple => apple.Weight > 300);
applesOver300 = apples.Where(apple => apple.Weight > 300).ToList();
List<Apple> FilterApfel(List<Apple> apfels, Func<Apple, bool> filter){
var result = new List<Apple>();
foreach(var apfel in apfels){
if(filter(apfel)){
result.Add(apfel);
}
}
return result;
}
List<Apple> FilterFarbeApfel(List<Apple> apfels, string color){
var result = new List<Apple>();
foreach(var apfel in apfels){
if(apfel.Color == color){
result.Add(apfel);
}
}
return result;
}
List<Apple> FilterWeightApfel(List<Apple> apfels, int weight){
var result = new List<Apple>();
foreach(var apfel in apfels){
if(apfel.Weight == weight){
result.Add(apfel);
}
}
return result;
}
public class Apple{
public string Color { get; set; }
public int Weight { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment