2013-07-05 44 views
10

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ị.

+5

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? –

Trả lời

5

Nếu bạn muốn nhóm các quốc gia theo mã, thì bạn không cần hai từ điển. Sử dụng Enumerable.GroupBy

foreach(var codeGroup in countries.GroupBy(c => c.CountryCode)) 
{ 
    foreach(var country in codeGroup) 
     Console.WriteLine(country.CountryName); 

    Console.WriteLine(); 
} 

Hoặc chỉ cần sử dụng của bạn countriesDictionary (nó đã có các nước nhóm lại theo code):

foreach(var kvp in countriesDictionary) 
{ 
    foreach(var country in kvp.Value) 
     Console.WriteLine(country.CountryName); 

    Console.WriteLine(); 
} 
10

Đây là một thay thế:

countriesDictionary.ToList().ForEach 
(
    pair => 
    { 
     pair.Value.ForEach(country => Console.WriteLine(country.CountryName)); 
     Console.WriteLine(); 
    } 
); 

Ngoài ra, chương trình này dựa trên Romoku's Answer (nswer đã được gỡ bỏ):

var countriesDictionary = countries.ToLookup(x => x.CountryCode, x => x); 

var dCountries = new List<Country>(); 

foreach(var countryGroup in countriesDictionary) 
{ 
    foreach(var country in countryGroup) 
    { 
     Console.WriteLine(country.CountryName); 
    } 
    Console.WriteLine(); 
} 
1

Hoặc chỉ cần làm cho nó rất dễ dàng ... như đã đề cập, bạn đã nhóm bởi Mã quốc gia ...

 foreach (var country in countriesDictionary.SelectMany(pair => pair.Value)) 
     { 
      Console.WriteLine(country.CountryName); 
     } 
0

tôi sẽ sử dụng một phần mở rộng để làm nó.

static class CountryExtension 
    { 
     public static void WriteCountriesGroupyCountryCode(this IEnumerable<Country> list) 
     { 
      int currentCountry=int.MinValue; 
      list.OrderBy(c => c.CountryCode).ThenBy(c=>c.CountryName).ToList().ForEach(c => 
      { 
       if (currentCountry == int.MinValue) 
       { 
        currentCountry = c.CountryCode; 
       } 
       else if (currentCountry != c.CountryCode) 
       { 
        Console.WriteLine(); 
        currentCountry = c.CountryCode; 
       } 
       Console.WriteLine(c.CountryName); 
      }); 
     } 
    } 
1

Một cách có thể là như thế này, tránh foreach đầu tiên với groupby, logic chỉ 1 foreach để in mỗi tên đất nước với mã đã chỉ định:

Dictionary<int, List<Country>> countriesDictionary = countries.GroupBy(g => g.CountryCode).ToDictionary(k => k.Key, k => k.ToList()); 

foreach (int key in countriesDictionary.Keys) 
{ 
     Console.WriteLine("****Countries with code {0}****",key); 
     int count = 0; 
     while (count < countriesDictionary[key].Count) 
     { 
      Console.WriteLine(countriesDictionary[key][count].CountryName); 
      count++; 
     } 
     Console.WriteLine(); 
} 

Console.ReadLine(); 
1

Mặc dù bạn có thể có đủ câu trả lời cho Hiện tại, LINQ này sẽ nén từ điển của bạn thành một danh sách tên quốc gia, cho phép bạn dễ dàng hiển thị chúng.

List<string> countryNames = countriesDictionary.SelectMany(
     pair=>pair.Value.Where(
      country=>country.CountryCode == pair.Key 
     ).Select(x=>x.CountryName)).ToList(); 

    foreach (var name in countryNames) 
     Console.WriteLine(name); 

Nhưng cách từ điển của bạn được thiết lập, khóa phải luôn khớp với mã quốc gia có giá trị đúng không?

Các vấn đề liên quan