[英]How do I get quoted fields from a delimited string as a list of unquoted values using LINQ?
Original text line is: "125"|"Bio Methyl"|"99991"|"OPT12"|"CB"|"1"|"12"|"5"|"23"
原始文本行是:
"125"|"Bio Methyl"|"99991"|"OPT12"|"CB"|"1"|"12"|"5"|"23"
Expected string list is free of double quotes and split by |
预期的字符串列表不包含双引号,并且由
|
分隔 : :
125
Bio Methyl
99991
The text may contain empty quoted strings as in (former "OPT12" value now empty ""): 文本中可能包含带引号的空字符串,如(以前的“ OPT12”值现在为空的“”):
"125"|"Bio Methyl"|"99991"|""|"CB"|"1"|"12"|"5"|"23"
So I checked these two questions & answers : QA1 and QA2 to derive my solution. 因此,我检查了以下两个问题和答案: QA1和QA2以得出我的解决方案。
var eList = uEList.ElementAt(i).Split(BarDelimiter);
var xList = eList.ElementAt(0).Where(char.IsDigit).ToList();
Of course it doesn't work the way I need it to be since xList
is a list with elements like this: xList(0) = 1, xList(1) = 2, xList(2) = 5
当然,它不符合我的需要,因为
xList
是一个包含以下元素的列表: xList(0) = 1, xList(1) = 2, xList(2) = 5
I do not want to write another line to join them because this doesn't look like a suitable solution. 我不想再写一行加入他们,因为这看起来不合适。 There has to be something better with LINQ right?
LINQ一定有更好的选择吧?
How about this: 这个怎么样:
// Based on OPs comment: preserve empty non-quoted entries.
var splitOptions = StringSplitOptions.None;
//change to the below if empty entries should be removed
//var splitOptions = StringSplitOptions.None;
var line = "\"125\"|\"Bio Methyl\"|\"99991\"|\"OPT12\"|\"CB\"|\"1\"|\"12\"|\"5\"|\"23\"";
var result = line
.Split(new[] { "|" }, splitOptions)
.Select(p => p.Trim('\"'))
.ToList();
Console.WriteLine(string.Join(", ", result));
The Split(...)
statement splits the input into an array with parts like Split(...)
语句将输入拆分成一个数组,其中包括
{ \"99991\", \"OPT12\", ... };
The p.Trim('\\"')
statement removes the leading and trailing quote from each of the parts. p.Trim('\\"')
语句从每个部分中删除前导和尾随引号。
As an alternative to the trimming, if there's no "
in your values, you could simply sanitize the input before splitting it. You can do so by replacing the "
symbol by nothing (either ""
or string.Empty
). 作为修剪的替代方法,如果您的值中没有
"
,则可以在拆分输入之前先对其进行清理。您可以通过不使用""
符号( ""
或“ string.Empty
)替换"
符号来进行此处理。
Your Split
code would then give the correct result afterwards: 然后,您的
Split
代码将给出正确的结果:
string uEList = "\"125\"|\"Bio Methyl\"|\"99991\"|\"OPT12\"|\"CB\"|\"1\"|\"12\"|\"5\"|\"23\"";
var eList = uEList.Replace("\"", string.Empty).Split(BarDelimiter);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.