1

我有一个字典对象如下

Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>();
dictStr.Add("Culture", new List<string>() { "en-US", "fr-FR" });
dictStr.Add("Affiliate", new List<string>() { "0", "1" });
dictStr.Add("EmailAddress", new List<string>() { "sreetest@test.com", "somemail@test.com" });

我有一个实体如下

public class NewContextElements
{ 
    public string Value { get; set; }
}

我需要做的是,对于字典值集合的特定索引中的每个值,我必须制作一个逗号分隔的字符串并将其放入 List 集合中。

例如 NewContextElements 集合将具有(显然在运行时)

var res = new List<NewContextElements>();
res.Add(new NewContextElements { Value = "en-US" + "," + "0" + "," + "sreetest@test.com" });
res.Add(new NewContextElements { Value = "fr-FR" + "," + "1" + "," + "somemail@test.com" });

我正在尝试

var len = dictStr.Values.Count;
for (int i = 0; i < len; i++)
{
    var x =dictStr.Values[i];
}

不,这当然是不正确的。

需要帮助

4

3 回答 3

2

尝试这个:

Enumerable.Range(0, len).Select( i =>
    new NewContextElements {
        Value = string.Join(",", dictStr.Values.Select(list => list[i]))
    }
);

len是单个列表中的项目数(在您的示例中,它是两个)。

于 2012-05-11T02:52:58.700 回答
0

你的意思是转换你的数据像

1 2 
3 4
5 6

1 3 5
2 4 6

试试这段代码?它可以通过几种方式进行优化。

var res = new List<NewContextElements>();
int i = dictStr.values.count()
for (int i=0; i < len; i++) {

    NewContextElements newContextElements = new NewContextElements();

    foreach (List<string> list in dictStr) {

        if (newContextElements.value() == null ) {

            newContextElements.value = list[i];

        } else  {

            newContextElements.value += ", " + list[i] );
        }      
    }
    res.add(newContextElements);
}

让我知道代码中是否存在问题,就像您在没有真正 ide 的情况下编写代码时出现的问题一样。

于 2012-05-11T03:02:58.547 回答
0

这不像@dasblinkenlight 的解决方案那样巧妙,但它应该可以工作:

        Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>( );
        dictStr.Add( "Culture", new List<string>( ) {"en-US", "fr-FR"} );
        dictStr.Add( "Affiliate", new List<string>( ) {"0", "1"} );
        dictStr.Add( "EmailAddress", new List<string>( ) {"sreetest@test.com", "somemail@test.com"} );

        int maxValues = dictStr.Values.Select(l => l.Count).Max(); 
        List<NewContextElements> resultValues = new List<NewContextElements>(dictStr.Keys.Count);
        for (int i = 0; i < maxValues; i++) {
            StringBuilder sb = new StringBuilder();
            string spacer = string.Empty;
            dictStr.Keys.ForEach( k => {
                                    sb.AppendFormat( "{0}{1}", spacer, dictStr[k][i] );
                                    spacer = ", ";
                                  } );
            resultValues.Add( new NewContextElements(  ){ Value = sb.ToString() });
        }
于 2012-05-11T03:06:11.590 回答