简体   繁体   English

如何将ac#逗号分隔值字符串转换为列表?

[英]How to convert a c# comma separated values string into a list?

I'm using C# ASP.NET 4 and SQL Server 2008 R2 我正在使用C#ASP.NET 4和SQL Server 2008 R2

I'm getting an object scalar from sql server which is a string containing comma separated values of the form: 我从sql server得到一个对象标量,它是一个字符串,其中包含以下形式的逗号分隔值:

7, 12, ... 1, 65

I would like to convert this object into a list? 我想将此对象转换为列表吗?

I thought of the direction: 我想到了方向:

List<int> myList = new List<int>(new int[] (List)mySqlClass.mySqlQueryReturningAnObject("SELECT CLAUSE");

but this is not going to work. 但这是行不通的。

How do I convert this object into a list? 如何将此对象转换为列表?


Full answer: 完整答案:

This answer in use is according to the selected answer (before the update) 此答案正在使用中(根据更新之前的答案)

List<int> myList = new List<int>(mySqlClass.mySqlQueryReturningAnObject("SELECT CLAUSE").ToString().Split(',').Select(x => Convert.ToInt32(x)).ToList());

var intValues = line.Split(',').Select(x => Convert.ToInt32(x)).ToList();

Update 更新资料

To ensure your code would be able to process strings like 1,2,3,,,4,5,6 you can use overload of String.Split method 为了确保您的代码能够处理1,2,3,,,4,5,6类的字符串,您可以使用String.Split方法的重载

var intValues = line.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => Convert.ToInt32(x))
                    .ToList();

Use the .Split() method on the string. 在字符串上使用.Split()方法。 It will return an array of strings. 它将返回一个字符串数组。

string yourResult = "1,2,3,4,5";
string[] resultsArray = yourResult.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);

Did you try String.Split ? 您尝试过String.Split吗?

You can split your string with a line as simple as this: 您可以使用这样的简单行来分割字符串:

var myString="1,2,4,5,6";
var numberList=myString.Split(',');

You can use simple Array.ConvertAll instuction, like this: 您可以使用简单的Array.ConvertAll指令,如下所示:

string str = "1,2,3,4,5,7,8,9";
int[]resultInArray = Array.ConvertAll( str.Split(','), item => int.Parse(item));
        private void TestParse()
        {
            string commaseparatedstring = "3, 5,6,19";

            int parsedvalue = 0;

            List<int> valuesint =
                commaseparatedstring.Split(',').Select(elem => int.TryParse(elem, out parsedvalue) ? parsedvalue : 0).ToList(); 

        }

You could try assigning the result to a variable. 您可以尝试将结果分配给变量。

Then convert it into a string (if its not already one) 然后将其转换为字符串(如果尚未转换为字符串)

Then do a string split on the comma and assigning the results to a list. 然后在逗号上进行字符串拆分,并将结果分配给列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM