Simply IEnumerable<int> to List<KeyValuePair<int, int>>?

The following code works fine:

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

But is there a better way to simplify the conversion? (eg. eliminating ToDictionary?)

Jon Skeet
people
quotationmark

Sure, just use Select:

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

It's not clear whether you need this to be List<T>, but doing so guarantees that it's only going to be evaluated once, and may allow some optimizations in whatever you're using.

There's no need to create a Dictionary - and indeed, by doing so you're currently not guaranteeing the ordering, whereas the above code will definitely give you 1-31 in order.

people

See more on this question at Stackoverflow