0

我必须在 c# 中拆分逗号分隔的字符串,并且需要将其保存在两个变量中。C#函数如下:

public int InsertLogDetails(string RunIDStartTime, int Distribution_ID, List<string> additions, List<string> removals, bool status, string ErrorMessage)
{
    int Run_ID=0;
    DateTime StartTime=DateTime.Now;
    //Needs to split RunIDStartTime and needs to save it in Run_ID and StartTime
}

RunIDStartTime 保存 Run_ID 和 StartTime 的值。(例如:5,Jan 23 2013 9:31AM)

任何人请帮忙。提前致谢。

4

3 回答 3

3

这是一个有效的答案,您不需要执行 .ToArray ,因为 Split 已经返回了一个数组。

var RunIDStartTime = "5,Jan 23 2013 9:31AM";
var listSplit = RunIDStartTime.Split(','); 
var id = int.Parse(listSplit[0]);
var dateTime = DateTime.Parse(listSplit[1]);

returns id = 5 and date = Jan 23 2013 9:31AM

于 2013-01-24T06:33:17.567 回答
1

使用int.TryParseandDateTime.TryParseExact和 DateFormat 来解析字符串。要拆分,使用string.Split,例如:

string RunIDStartTime = "5,Jan 23 2013 9:31AM";

int Run_ID = 0;
DateTime StartTime = DateTime.MinValue;
string[] splittedArray = RunIDStartTime.Split(',');
if (splittedArray.Length >= 2)
{
    if (int.TryParse(splittedArray[0], out Run_ID))
    {
        //valid ID
    }
    else
    {
        //Invalid ID
    }
    if(DateTime.TryParseExact(splittedArray[1],"MMM d yyyy h:mmtt",CultureInfo.InvariantCulture,DateTimeStyles.None, out StartTime))
    {
        //Valid date
    }
    else
    {
        //invalid date
    }
}

对于输出:

Console.WriteLine("ID : {0} Date: {1}", Run_ID, StartTime.ToString());

输出:

ID : 5 Date: 23/01/2013 9:31:00 AM
于 2013-01-24T06:33:19.280 回答
0
public int InsertLogDetails(string RunIDStartTime, int Distribution_ID, List<string> additions, List<string> removals, bool status, string ErrorMessage)
{

    var tokens = RunIDStartTime.split(',');
    int Run_ID= int.Parse(tokens[0]);
    DateTime StartTime = DateTime.Parse(tokens[1],"MMM d yyyy h:mmtt", CultureInfo.InvariantCulture, DateTimeStyles.None);        
}
于 2013-01-24T06:41:50.233 回答