简体   繁体   English

如何将两个不同类型的列表合并为一个包含两种类型的新类型列表?

[英]How to merge two lists of different types into one list of new type that contains both types?

I want to combine/merge/join/whatever a list of enum s, so that each item in the unified list will have two fields - the name of the enum item ( string Name ), and its value ( TokensEnum Token ): 我想组合/合并/加入/无论enum列表如何,以便统一列表中的每个项目都有两个字段 - enum项的string Namestring Name )及其值( TokensEnum Token ):

var tokens = Enum.GetValues(typeof (TokensEnum));
var names = Enum.GetNames(typeof (TokensEnum));

var combined = InTheDarknessBindThem(tokens,names);

foreach(var c in combined)
    MessageBox.Show(string.Format(
        "Token \"{0}\" value is {1}", c.Name, (int)c.Token));

How to write the body of the following method (preferably LINQ-wise)? 如何编写以下方法的主体(最好是LINQ方式)?

InTheDarknessBindThem(IEnumerable<TokensEnum> tokens, IEnumerable<string> names) {
    /*
        ...
    */
}

If both lists are in order, you can use the Zip extension method: 如果两个列表都是有序的,您可以使用Zip扩展方法:

tokens.Cast<TokensEnum>().Zip(names, (t, n) => Tuple.Create(t, n));

This will return an IEnumerable<Tuple<TokensEnum, string>> . 这将返回一个IEnumerable<Tuple<TokensEnum, string>>

But as Jon Skeet suggests , in this case, it would probably be easier to do something like this: 但正如Jon Skeet所暗示的那样 ,在这种情况下,做这样的事情可能会更容易:

Enum.GetValues(typeof(TokensEnum))
    .Cast<TokensEnum>()
    .Select(t => Tuple.Create(t, t.ToString()));

This will return the same result as above, but it will do it in a single step. 这将返回与上面相同的结果,但它将在一个步骤中完成。

Since you mentioned in your comments that you'd like to have a Dictionary<string, TokensEnum> , you can use something like this to construct it: 既然你在评论中提到你想要一个Dictionary<string, TokensEnum> ,你可以使用这样的东西来构造它:

Dictionary<string, TokensEnum> myDictionary = 
    Enum.GetValues(typeof(TokensEnum))
        .Cast<TokensEnum>()
        .ToDictionary(t => t.ToString());

Why not a dictionary? 为什么不是字典?

var dict = Enum.GetValues(typeof (TokensEnum))
               .Cast<TokensEnum>()
               .ToDictionary(x => x, x => x.ToString());
foreach (var kvp in dict)
{
    Console.WriteLine("Value: {0}, Name: {1}",kvp.Key,kvp.Value);
}

The printout is a bit moot since ToString() is called on value. 由于在值上调用ToString(),打印输出有点没有实际意义。

I think using enum as key in a dictionary cases boxing. 我认为使用枚举作为字典案例拳击的关键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM