Làm cách nào để viết triển khai vòng lặp "// Hiển thị sử dụng Foreach" bằng LINQ Lambda Expression/Statemene Expression?Xử lý từ điển C# bằng cách sử dụng LINQ
Tôi muốn đơn giản hóa sự phát triển của mình và tránh các vòng lặp forested lồng nhau càng nhiều càng tốt. Tôi đang cố gắng bao gồm nhiều logic hơn trong tuyên bố foreach thứ hai và tôi muốn sử dụng biểu thức 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();
}
Vui lòng đề nghị.
Bạn đã có các quốc gia được lọc trong từ điển 'countriesDictionary', tại sao bạn tìm kiếm trong' dCountries' trong vòng lặp lồng nhau? –