2009-11-29 14 views
10

¿Es posible declarar implícitamente próxima Dictionary<HyperLink, Anonymous>:Anónimo inicializador de colección para un diccionario

{ urlA, new { Text = "TextA", Url = "UrlA" } }, 
{ urlB, new { Text = "TextB", Url = "UrlB" } } 

así que podía usar de esta manera:

foreach (var k in dic) 
{ 
    k.Key.Text = k.Value.Text; 
    k.Key.NavigateUrl = k.Value.Url; 
} 

?

+0

posible duplicado de [Un diccionario donde el valor es un tipo anónimo en C#] (http://stackoverflow.com/questions/1619518/a-dictionary-where-value-is-an-anonymous-type-in-c -sharp) – nawfal

Respuesta

16

¿Qué tal:

var dict = new[] { 
      new { Text = "TextA", Url = "UrlA" }, 
      new { Text = "TextB", Url = "UrlB" } 
     }.ToDictionary(x => x.Url); 
// or to add separately: 
dict.Add("UrlC", new { Text = "TextC", Url = "UrlC" }); 

Sin embargo, sólo podría foreach en una lista/gama ...

var arr = new[] { 
    new { Text = "TextA", Url = "UrlA" }, 
    new { Text = "TextB", Url = "UrlB" } 
}; 
foreach (var item in arr) { 
    Console.WriteLine("{0}: {1}", item.Text, item.Url); 
} 

Sólo necesita un diccionario si necesita O (1) a través de la consulta de (llave unica.

1

Sí, pero solo con una gran solución, y solo dentro de un método.

Esta es la forma en que puede hacerlo:

static Dictionary<TKey, TValue> NewDictionary<TKey, TValue>(TKey key, TValue value) 
    { 
     return new Dictionary<TKey, TValue>(); 
    } 
    public void DictRun() 
    { 

     var myDict = NewDictionary(new { url="a"}, 
      new { Text = "dollar", Url ="urlA"}); 
     myDict.Add(new { url = "b" }, new { Text = "pound", Url = "urlB" }); 
     myDict.Add(new { url = "c" }, new { Text = "rm", Url = "urlc" }); 
     foreach (var k in myDict) 
     { 
      var url= k.Key.url; 
      var txt= k.Value.Text; 

      Console.WriteLine(url); 
      Console.WriteLine(txt);  
     } 

    } 

Se puede hacer referencia a esta SO question para obtener más información.

+0

no responde la pregunta, argumentos no utilizados ... – Behrooz

Cuestiones relacionadas