티스토리 뷰
목차
C# List + Lambda + Linq 문법 예제 13개, 람다 리스트 축약
List 객체에 데이터를 저장할 경우 Lambda를 활용하면 더 간단하게 소스 코드를 구성할 수 있습니다. 아래는 그 예제입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Person { public string SSN; public string Name; public string Address; public int Age; public Person(string ssn, string name, string addr, int age) { SSN = ssn; Name = name; Address = addr; Age = age; } } | cs |
사람 정보(Person 클래스 객체)를 생성하여 List에 삽입합니다. 이어서, 특정 조건으로 Person 리스트를 순회할 겁니다.
람다 문법을 활용해 원하는 결과도 얻어 볼 겁니다.
1 2 3 4 5 6 7 8 9 10 11 | List<Person> listPersonsInCity = new List<Person>(); listPersonsInCity.Add(new Person("203456876", "John", "12 Main Street, Newyork, NY", 15)); listPersonsInCity.Add(new Person("203456877", "SAM", "13 Main Ct, Newyork, NY", 25)); listPersonsInCity.Add(new Person("203456878", "Elan", "14 Main Street, Newyork, NY", 35)); listPersonsInCity.Add(new Person("203456879", "Smith", "12 Main Street, Newyork, NY", 45)); listPersonsInCity.Add(new Person("203456880", "SAM", "345 Main Ave, Dayton, OH", 55)); listPersonsInCity.Add(new Person("203456881", "Sue", "32 Cranbrook Rd, Newyork, NY", 65)); listPersonsInCity.Add(new Person("203456882", "Winston", "1208 Alex St, Newyork, NY", 65)); listPersonsInCity.Add(new Person("203456883", "Mac", "126 Province Ave, Baltimore, NY", 85)); listPersonsInCity.Add(new Person("203456884", "SAM", "126 Province Ave, Baltimore, NY", 95)); | cs |
이제 한 줄 짜리 람다 표현식을 사용해 다양한 복합 연산 수행 방법을 알아 보겠습니다.
1. 60세 이상인 사람 2명을 검색
1 2 3 4 5 6 | Console.WriteLine("Retrieving Top 2 aged persons from the list who are older than 60 years\n"); foreach (Person person in listPersonsInCity.FindAll(e => (e.Age >= 60)).Take(2).ToList()) { Console.WriteLine("Name : " + person.Name + " \t\tAge: " + person.Age); } | cs |
결과
Retrieving Top 2 aged persons from the list who are older than 60 years
Name : Sue Age : 65
Name : Winston Age : 65
람다 Linq
2. 13~19세 사이 청소년을 리스트에서 검색
1 2 3 4 5 6 | Console.WriteLine("\nChecking whether any person is teen-ager or not..."); if (listPersonsInCity.Any(e => (e.Age >= 13 && e.Age <= 19))) { Console.WriteLine("Yes, we have some teen-agers in the list"); } | cs |
결과
Checking whether any person is teen-ager or not...
Yes, we have some teen-agers in the list
3. 모두 나이가 10세 이상인지
1 2 3 4 5 6 | Console.WriteLine("\nCheking whether all the persons are older than 10 years or not..."); if ( listPersonsInCity.All(e => (e.Age > 10))) { Console.WriteLine("Yes, all the persons older than 10 years"); } | cs |
결과
Checking whether all the persons are older than 10 years or not...
Yes, All the persons older than 10 years
4. 모든 사람을 대상으로 평균 연령 구하기
1 2 3 4 5 | Console.WriteLine("\nGetting Average of all the person's age..."); double avgAge = listPersonsInCity.Average(e => e.Age); Console.WriteLine("The average of all the person's age is: "+ avgAge); | cs |
결과
Getting Average of all the person's age...
The average of all the person's age is : 53.9
5. SAM이란 이름을 검색
1 2 3 4 5 6 | Console.WriteLine("\nChecking whether a person having name 'SAM' exists or not..."); if (listPersonsInCity.Exists(e => e.Name == "SAM")) { Console.WriteLine("Yes, A person having name 'SAM' exists in our list"); } | cs |
결과
Checking whether a person having name 'SAM' exists or not...
Yes, A person having name 'SAM' exists in our list
Linq
6. Smith 인덱스 위치 알아내기 (리스트 인덱스)
1 2 3 4 5 | Console.WriteLine("\nChecking the index position of a person having name 'Smith' ..."); int indexForSmith = listPersonsInCity.FindIndex(e => e.Name == "Smith"); Console.WriteLine("In the list, The index position of a person having name 'Smith' is : " + indexForSmith); | cs |
결과
Checking the index position of a person having name 'Smith' ...
In the list, The index position of a person having name 'Smith' is : 3
7. 나이가 가장 많은 사람
1 2 3 4 5 | Console.WriteLine("\nGetting the name of the most aged person in the list ..."); Person p = listPersonsInCity.First(m=> m.Age == (listPersonsInCity.Max(e => e.Age))); Console.WriteLine("The most aged person in our list is: "+ p.Name +" whose age is: "+ p.Age); | cs |
결과
Getting the name of the most aged person in the list ...
The most aged person in our list is: SAM whose age is: 95
8. 모든 사람의 나이 합
1 2 3 4 5 | Console.WriteLine("\nGetting Sum of all the person's age..."); int sumOfAges = listPersonsInCity.Sum(e => e.Age); Console.WriteLine("The sum of all the persons's age = "+ sumOfAges); | cs |
결과
Getting Sum of all the person's age...
The sum of all the persons's age = 485
9. 60세 이상인 사람 리스트
1 2 3 4 5 6 | Console.WriteLine("\nSkipping every person whose age is less than 60 years..."); foreach (Person pers in listPersonsInCity.SkipWhile(e => e.Age < 60)) { Console.WriteLine("Name : "+ pers.Name + " \t\tAge: "+ pers.Age); } | cs |
결과
Skipping every person whose age is less than 60 years...
Name : Sue Age : 65
Name : Winston Age : 65
Name : Mac Age : 85
Name : SAM Age : 95
람다 Linq
10. 이름이 J로 시작하는 사람 찾기
1 2 3 4 5 6 | Console.WriteLine("Displaying the persons until we find a person with name starts with other than 'S'"); foreach (Person pers in listPersonsInCity.TakeWhile(e => e.Name.StartsWith("J"))) { Console.WriteLine("Name : " + pers.Name + " \t\tAge: " + pers.Age); } | cs |
결과
Displaying the persons until we find a person with name starts with other than 'S'
Name : John Age : 15
11. 모든 사람이 SSN을 가지고 있는지 확인
1 2 3 4 5 6 | Console.WriteLine("\nChecking all the persons have SSN or not ..."); if(listPersonsInCity.TrueForAll(e => e.SSN != null)) { Console.WriteLine("No person is found without SSN"); } | cs |
결과
Checking all the persons have SSN or not ...
No person is found without SSN
람다 Linq
12. C# 리스트에서 SAM 이름 가진 사람 삭제
1 2 3 4 5 6 7 | Console.WriteLine("\nRemoving all the persons record from list that have "SAM" name"); listPersonsInCity.RemoveAll(e => (e.Name == "SAM")); if (listPersonsInCity.TrueForAll(e => e.Name != "SAM")) { Console.WriteLine("No person is found with 'SAM' name in current list"); } | cs |
결과
Removing all the persons record from list that have "SAM" name
No person is found with 'SAM' name in current list
13. SSN 코드 203456876 검색
1 2 3 4 5 | Console.WriteLine("\nFinding the person whose SSN = 203456876 in the list"); Person oPerson = listPersonsInCity.Find(e => (e.SSN == "203456876")); Console.WriteLine("The person having SSN '203456876' is : " + oPerson.Name + " \t\tAge: " + oPerson.Age); | cs |
결과
Removing all the persons record from list that have "SAM" name
No person is found with 'SAM' name in current list
C# List + Lambda + Linq 문법 예제 13개, 람다 리스트 축약