Ari*_*ion 27 c# linq linq-to-sql
所以我有一个字符串列表,如下所示:
var ls=new List<string>()
{
"100",
"101-102-1002",
"105-153-1532-1532",
"105-1854-45-198",
"180-95-45-200"
};
Run Code Online (Sandbox Code Playgroud)
我想得到分裂字符串的倒数第二个.所以我的输出看起来像这样:
null,
102,
1532,
45,
45
Run Code Online (Sandbox Code Playgroud)
我有一个解决方案,看起来像这样:
ls.Select (l =>l.Split('-').Select ((s,i) =>new {s,i})
.OrderByDescending (x=>x.i).Skip(1).Take(1))
Run Code Online (Sandbox Code Playgroud)
我认为这个解决方案对于这个简单的任务可能很复杂.所以我的问题是:你们有没有更简单的解决方案来解决这个问题?
Pav*_*lov 37
Reverse 适合这里:
ls.SelectMany(l =>l.Split('-').Reverse().Skip(1).Take(1).DefaultIfEmpty())
Run Code Online (Sandbox Code Playgroud)
我也用SelectMany变换IEnumerable<IEnumerable<string>>来<IEnumerable<string>.
she*_*bin 12
var ls = new List<string>() { "100", "101-102-1002", "105-153-1532-1532", "12-1235-785" };
var result = from p in ls
let arr = p.Split('-')
select arr.Length < 2 ? null : arr[arr.Length - 2];
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.Read();
Run Code Online (Sandbox Code Playgroud)
如果你有
var ls = new List<string>( ... );
然后
var result = ls.Reverse().Skip(1).Take(1);
应该管用.
var ls = new List<string>(){"100","101-102-1002","105-153-1532-1532","12-1235-785"};
var result = from l in ls
let s = l.Split('-')
select s.ElementAtOrDefault(s.Length - 2);
Run Code Online (Sandbox Code Playgroud)
\xc2\xa0 \xc2\xa0我已经根据上面的 \xc2\xa0Pavel Gatilov 的答案创建了一个扩展
\n\npublic static TSource SecondLast<TSource>(this IEnumerable<TSource> source)\n{\n\xc2\xa0 \xc2\xa0 \xc2\xa0 //from http://stackoverflow.com/questions/8724179/linq-how-to-get-second-last\n\xc2\xa0 \xc2\xa0 \xc2\xa0 return source.Reverse().Skip(1).Take(1).FirstOrDefault();\n}\nRun Code Online (Sandbox Code Playgroud)\n