我想从时间格式列表中找到最长时间,它不完全是TimeSpan
所以解析它无济于事。
请提出解决方案。
var duration = new List<string>() { "116:48:28", "110:36:28", "16:30:28"};
var maxts = duration.Max(x => TimeSpan.Parse(x));
答案 0 :(得分:3)
你可以试试这个。它会起作用,你不会有像#'s 1:70:10&#34; ......
duration.Select(d=>d.Replace(":", string.Empty)).Select(int.Parse).OrderBy(s=>s)
或者,获取最大时间戳的值:
duration.Select(d => new {Text =d, Val = int.Parse(d.Replace(":", string.Empty))})
.OrderByDescending(x=>x.Val)
.First()
.Text;
答案 1 :(得分:2)
您可以使用var sortedDuraion = duration
.OrderByDescending((s) => Convert.ToInt32(s.Split(':')[0]))
.ThenByDescending((s) => Convert.ToInt32(s.Split(':')[1]))
.ThenByDescending((s) => Convert.ToInt32(s.Split(':')[2]));
var max = sortedDuration.ElementAt(0);
:
string
您也可以将此int
解析为":"
(删除int
)并订购var sortedDuration = duration.OrderByDescending((s) => Convert.ToInt32(s.Replace(":", String.Empty)));
var max = sortedDuration.ElementAt(0);
值:
HTTParty
答案 2 :(得分:0)
你可以这样尝试
var duration = new List<string>() { "116:48:28", "110:36:28", "16:30:28" };
List<TimeSpan> lst = new List<TimeSpan>();
foreach (var item in duration)
{
string[] data=item.Split(new char[]{':'});
lst.Add(new TimeSpan(int.Parse(data[0]),int.Parse(data[1]),int.Parse(data[2])));
}
var max = lst.Max();
答案 3 :(得分:0)
您可以使用正则表达式:
internal static TimeSpan ParseSpecialTimespan(string toParse)
{
string pattern = @"^(\d+):([0-5]?\d{1}):([0-5]?\d{1})$";
var match = Regex.Match(toParse, pattern);
if (!match.Success) throw new ArgumentException(@"The provided string is not valid...");
int hours = int.Parse(match.Groups[1].ToString());
int minutes = int.Parse(match.Groups[2].ToString());
int seconds = int.Parse(match.Groups[3].ToString());
TimeSpan t = new TimeSpan(hours, minutes, seconds);
return t;
}
以下是如何使用的:
var duration = new List<string>() { "116:48:28", "110:36:28", "16:30:28" };
string largestInput = "";
TimeSpan largestTimespan = new TimeSpan(0);
foreach (string d in duration)
{
TimeSpan parse = ParseSpecialTimespan(d);
if (parse > largestTimespan)
{
largestTimespan = parse;
largestInput = d;
}
}
System.Diagnostics.Debug.Print(@"Largest timespan is ""{0}"" from input ""{1}"".", largestTimespan.ToString(), largestInput);