LINQ查询解析List并根据首字符获取多个分组
LINQ query to parse List and get multiple groups based on the initial character
问候大师,我有一个解析文本文件的 LINQ 查询。
var p = from n in File.ReadAllLines(@"D:\data.txt")
where n.StartsWith("-"||"/")
select n;
我收到有关 or 运算符 ||
不能应用于字符串的错误?!
我正在尝试获取以不同开关开头的行组(一组 /
和一组 -
.
你想要这个:
IEnumerable<string> p =
from n in File.ReadAllLines(@"D:\data.txt")
where n.StartsWith("-") || n.StartsWith("/")
select n;
如果你还想按第一个字符分组,试试这个:
IEnumerable<IGrouping<char, string>> p =
from n in File.ReadAllLines(@"D:\data.txt")
where n.Length > 1
let k = n[0]
where k == '-' || k == '/'
group n by k;
也许你需要这个:
ILookup<char, string> p =
File
.ReadAllLines(@"D:\data.txt")
.Where(n => n.Length > 1 && (n[0] == '-' || n[0] == '/'))
.ToLookup(n => n[0], x => x);
IEnumerable<string> startsWithHyphen = p['-'];
IEnumerable<string> startsWithSlash = p['/'];
问候大师,我有一个解析文本文件的 LINQ 查询。
var p = from n in File.ReadAllLines(@"D:\data.txt")
where n.StartsWith("-"||"/")
select n;
我收到有关 or 运算符 ||
不能应用于字符串的错误?!
我正在尝试获取以不同开关开头的行组(一组 /
和一组 -
.
你想要这个:
IEnumerable<string> p =
from n in File.ReadAllLines(@"D:\data.txt")
where n.StartsWith("-") || n.StartsWith("/")
select n;
如果你还想按第一个字符分组,试试这个:
IEnumerable<IGrouping<char, string>> p =
from n in File.ReadAllLines(@"D:\data.txt")
where n.Length > 1
let k = n[0]
where k == '-' || k == '/'
group n by k;
也许你需要这个:
ILookup<char, string> p =
File
.ReadAllLines(@"D:\data.txt")
.Where(n => n.Length > 1 && (n[0] == '-' || n[0] == '/'))
.ToLookup(n => n[0], x => x);
IEnumerable<string> startsWithHyphen = p['-'];
IEnumerable<string> startsWithSlash = p['/'];