Cast List to List in .NET 2.0

后端 未结 8 2122
抹茶落季
抹茶落季 2020-12-07 15:28

Can you cast a List to List somehow?

I know I could loop through and .ToString() the thing, but a cast would be aw

相关标签:
8条回答
  • 2020-12-07 15:45

    Updated for 2010

    List<int> l1 = new List<int>(new int[] { 1,2,3 } );
    List<string> l2 = l1.ConvertAll<string>(x => x.ToString());
    
    0 讨论(0)
  • 2020-12-07 15:48

    .NET 2.0 has the ConvertAll method where you can pass in a converter function:

    List<int>    l1 = new List<int>(new int[] { 1, 2, 3 } );
    List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });
    
    0 讨论(0)
  • 2020-12-07 15:50

    You have to build a new list. The underlying bit representations of List<int> and List<string> are completely incompatible -- on a 64-bit platform, for instance, the individual members aren't even the same size.

    It is theoretically possible to treat a List<string> as a List<object> -- this gets you into the exciting worlds of covariance and contravariance, and is not currently supported by C# or VB.NET.

    0 讨论(0)
  • 2020-12-07 15:52

    Is C# 2.0 able to do List<T>.Convert? If so, I think your best guess would be to use that with a delegate:

    List<int> list = new List<int>();
    list.Add(1);
    list.Add(2);
    list.Add(3);
    list.Convert(delegate (int i) { return i.ToString(); });
    

    Something along those lines.


    Upvote Glenn's answer, which is probably the correct code ;-)

    0 讨论(0)
  • 2020-12-07 15:56

    result = listOfInt.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList()

    replace the parameters result and listOfInt to your parameters

    0 讨论(0)
  • 2020-12-07 16:07

    You can use:

    List<int> items = new List<int>(new int[] { 1,2,3 } );
    List<string> s = (from i in items select i.ToString()).ToList();
    
    0 讨论(0)
提交回复
热议问题