2013-07-05 14 views
10

LINQ Lambda Expression/Statemene Expressionを使用して "// Foreachを使用した表示"ループ実装を作成するにはどうすればよいですか?LINQを使用したC#ディクショナリの処理

開発を簡単にし、ネストされたforeachループをできるだけ避けたいと思います。私は2番目の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(); 
    } 

お勧めします。

+5

あなたは 'countriesDictionary'辞書の国をすでにフィルタリングしていますが、なぜネストされたループで' dCountries'を検索していますか? –

答えて

5

コードで国をグループ化する場合は、2つの辞書は必要ありません。 Enumerable.GroupBy

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

    Console.WriteLine(); 
} 

を使用するか、またはちょうどあなたのcountriesDictionary(それはすでに国がコードによってグループ化している)を使用します。

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

    Console.WriteLine(); 
} 
10

これは、別の代替案である。また、

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

、これを Romoku's Answer (a nswer)が削除されました:

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

それとも、それは非常に簡単に作る...すでに述べたように、すでに国コードによってグループ化している...

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

私が行うために拡張機能を使用しますそれ。

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

一つの方法は、指定されたコードで、それぞれの国の名前を印刷するには、ちょうど1 foreachのロジックをGROUPBYとの最初のforeachを避け、このようなことができます:

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

あなたはおそらくのための十分な答えを持っていますがLINQはあなたの辞書を国名のリストに圧縮し、容易にforeachに表示することができます。

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); 

しかし、あなたの辞書が設定されている方法、キーは常に正しい、価値の国コードと一致する必要がありますか?

関連する問題