Simply IEnumerable<int> to List<KeyValuePair<int

本文关键字:lt int List KeyValuePair to gt IEnumerable Simply | 更新日期: 2023-09-27 17:55:44

以下代码工作正常:

cboDay.DataSource = Enumerable.Range(1, 31).ToDictionary(x => x, x => x).ToList<KeyValuePair<int, int>>();
cboDay.ValueMember = "Key";
cboDay.DisplayMember = "Value";

但是有没有更好的方法来简化转换?(例如消除ToDictionary

Simply IEnumerable<int> to List<KeyValuePair<int

当然,只需使用 Select

cboDay.DataSource = Enumerable.Range(1, 31)
    .Select(x => new KeyValuePair<int, int>(x, x))
    .ToList();

目前尚不清楚您是否需要List<T>它,但这样做可以保证它只会被评估一次,并且可能允许您使用的任何内容进行一些优化。

没有必要创建一个Dictionary - 事实上,通过这样做,你目前不能保证排序,而上面的代码肯定会给你1-31的顺序。

确定您可以替换

Enumerable.Range(1, 31).ToDictionary(x => x, x => x).ToList<KeyValuePair<int, int>>();

Enumerable.Range(1, 31).Select(x => new KeyValuePair<int, int>(x,x)).ToList();