KeyValuePair列表 [英] List of KeyValuePair

查看:130
本文介绍了KeyValuePair列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么.NET不提供一个类为名单,其中,KeyValuePair< T,U>>

我认为当你需要保持对数组的形式也有很多的情况下。例如,

  1; 2的a; 阵列
5; 8的b; 浏览器
1; 9F; 火狐
8; 10F; 频率
 

一个LA:

 对< INT,INT> myPairs;

myPairs.Add(10,8);
myPairs.Add(5,8);
myPairs.Add(10,5);
myPairs.Add(1,4);

myPairs [0] .Value1 = 5;
myPairs [5] .Value2 = 8;
 

解决方案

这似乎完全没有必要我 - 只是因为你有一双价值并不意味着它一定是键/值的关系为

.NET 4中引入了元组系列的类型......除非真的的的一个键/值对,我会使用名单,其中元组LT; T1,T2>> 而不是 - 我看不出有任何理由为单一类型,以封装的结构存在

编辑:要把它放到上下文,这里是它的难是使用元组这里,将您的样品code:

  VAR myPairs =新名单,其中元组LT; INT,INT>> {
    Tuple.Create(10,8),
    Tuple.Create(5,8),
    Tuple.Create(10,5),
    Tuple.Create(1,4),
};
 

现在的元组是不可变的,所以你就不能直接按您的code中的最后部分设置的值...但美的构成的两个概念名单和对值是,你可以很容易地编写自己的 MutableTuple 键入和使用完全相同的code ...,而如果你有一个集合这是硬连接到元组或一些其他类型的类,你不会有这种灵活性。

Why does .NET not provide a class for a List<KeyValuePair<T, U>>?

I think there are a lot of situations when you need to keep an array of pairs. For example,

1; 2      "a"; "array"
5; 8      "b"; "browser"
1; 9      "f"; "Firefox"
8; 10     "f"; "frequency"

À la:

Pairs<int, int> myPairs;

myPairs.Add(10, 8);
myPairs.Add(5, 8);
myPairs.Add(10, 5);
myPairs.Add(1, 4);

myPairs[0].Value1 = 5;
myPairs[5].Value2 = 8;

解决方案

This seems completely unnecessary to me - and just because you have a pair of values doesn't mean it's necessarily a key/value relation either.

.NET 4 introduced the Tuple family of types... unless this really was a key/value pair, I'd use List<Tuple<T1, T2>> instead - and I see no reason for a single type to exist in order to encapsulate that construct.

EDIT: To put this into context, here's how "difficult" it is to use Tuple here, converting your sample code:

var myPairs = new List<Tuple<int, int>> {
    Tuple.Create(10, 8),
    Tuple.Create(5, 8),
    Tuple.Create(10, 5),
    Tuple.Create(1, 4),
};

Now tuples are immutable, so you wouldn't be able to set the values directly as per the last part of your code... but the beauty of composing the two concepts of "list" and "pair of values" is that you could easily write your own MutableTuple type and use exactly the same code... whereas if you had one collection class which was hard-wired to Tuple or some other type, you wouldn't have that flexibility.

这篇关于KeyValuePair列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆