错误“无法将类型“ System.Collections.Generic.IEnumerable <int>”隐式转换为“ System.Collections.Generic.List <int>”

时间:2018-10-25 20:40:38

标签: c#

我正在尝试将数字列表转换为字符串,然后再转换回列表。转换为字符串可以正常工作,但是当我将其转换回列表时,出现错误“无法隐式转换类型'System.Collections.Generic.IEnumerable'。这是我正在运行的代码。

using System;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.Globalization;

public class Test : MonoBehaviour
{

void Start()
{
    Function();
}

void Function()
{
    List<Int32> listBuffer= new List<Int32>();
    System.Random rnd = new System.Random();

    for (int x = 1; x < 100; x++)
    {
        listBuffer.Add(x);
    }

    List<Int32> listInt= (from item in listBuffer
                                      orderby rnd.Next()
                                      select item).ToList<Int32>();

    print(listInt[0]);

    string stringBuffer= String
                    .Join(
                    ", ",
    listInt.Select(n => n.ToString(CultureInfo.InvariantCulture))
    .ToArray()
    );
    print(stringBuffer);

    List<Int32> listInt2= stringBuffer
    .Split(',')
    .Select(c => Int32.Parse(c, CultureInfo.InvariantCulture));
    print(listInt2[0]);
}
}

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

List<Int32> listInt2 = stringBuffer
            .Split(',')
            .Select(c => Int32.Parse(c, CultureInfo.InvariantCulture)).ToList();

而不是:

List<Int32> listInt2 = stringBuffer
    .Split(',')
    .Select(c => Int32.Parse(c, CultureInfo.InvariantCulture));