LINQ Lambda Expression/Statemene Expression을 사용하여 "// Foreach를 사용하여 표시"루프 구현을 작성하려면 어떻게해야합니까?LINQ를 사용하여 C# 사전 처리
내 개발을 단순화하고 중첩 된 foreach 루프를 최대한 피하려고합니다. 나는 두 번째 foreach 문에서 더 많은 논리를 포함하려고 노력 중이며 Lambda/Statement 식을 사용하려고합니다.
internal class Program
{
internal class Country
{
public string CountryName { get; set; }
public int CountryCode { get; set; }
}
static void Main(string[] args)
{
List<Country> countries = new List<Country>()
{
new Country{CountryName = "India", CountryCode=1},
new Country{CountryName = "Andaman Nicobar", CountryCode=1},
new Country{CountryName = "United States of America", CountryCode=2},
new Country{CountryName = "Alaska", CountryCode=2},
new Country{CountryName = "Hawaii", CountryCode=2},
new Country{CountryName = "United Kingdom", CountryCode=3},
new Country{CountryName = "Australia", CountryCode=4}
};
Dictionary<int, List<Country>> countriesDictionary = new Dictionary<int, List<Country>>();
foreach (Country country in countries)
{
if (!countriesDictionary.ContainsKey(country.CountryCode))
countriesDictionary.Add(country.CountryCode, new List<Country>());
countriesDictionary[country.CountryCode].Add(country);
}
// Display using Foreach
foreach (int key in countriesDictionary.Keys)
{
List<Country> dCountries = countriesDictionary[key];
foreach (Country country in dCountries)
{
if (country.CountryCode.Equals(key))
{
Console.WriteLine(country.CountryName);
}
}
Console.WriteLine();
}
Console.ReadLine();
}
제안 해주십시오.
'countriesDictionary' 사전에 국가를 이미 필터링 했으므로 중첩 루프에서'dCountries'를 검색하는 이유는 무엇입니까? –