以下是我正在使用的CSV字符串。它在现实中要大得多,但这足以显示一种模式。
请注意,我已将此CSV放在单独的行上,只是为了轻松演示我的模式。
CSV分割后,字段数量可变,具体取决于原始字符串的大小,即字符串是可变长度,这使得索引数量可变
模式中的字母可能不总是P,可能是U,O或F
G9999999990001800002777107050,
G9999999990002777107HMNLAQKPRLLHRAQRWJ010,
1,
3,
29,
P,
6.74,
11.23,
07,
U,
5.25,
14.29,
08,
O,
6.89,
16.92,
07,
P,
5,
4,
我想拿起第5(29)和第6(P)元素,然后错过2个元素,然后选择下一个元素(07)和(P)之后的元素,依此类推,直到我到达结尾字符串。
在这个例子中我会有 29 P 07 P 08 P 07 P
有没有一种简单的方法可以做到这一点,我认为LINQ会提供一些东西
由于
答案 0 :(得分:4)
line.Split(',') //split on commas as it seems from your question that's your input
.Skip(2) //skip the first two entries
.Where((l, i) => i % 4 == 3 || i % 4 == 0) //take every 3rd and 4th item
.Skip(1); //skip the first item since the index is divisible by 4
但这根本没有描述代码的作用,我至少会发表评论。
答案 1 :(得分:2)
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<int> SpecialIndexes()
{
int i=4;
while (i<Int32.MaxValue)
{
yield return i++;
yield return i++;
i += 2;
}
}
public static void Main(string[] args)
{
var csvString = "G9999999990001800002777107050,G9999999990002777107HMNLAQKPRLLHRAQRWJ010,1,3,29,P,6.74,11.23,07,P,5.25,14.29,08,P,6.89,16.92,07,P,5,4,";
var fields = csvString.Split(',');
var selected = SpecialIndexes()
.TakeWhile(i => i<fields.Length)
.Select(i => fields[i]);
Console.WriteLine(string.Join(" ", selected.ToArray()));
}
}
29 P 07 P 08 P 07 P
答案 2 :(得分:0)
//Create a new variable of string
var x = string.Empty;
//Open a new FileStream
using (var fs = new FileStream(path,...))
//Open the StreamReader
using (var sr = new StreamReader(fs))
{
//Read out the whole CSV
x = sr.ReadToEnd();
}
//Split up the string by ',' and whitespaces. dismiss empty entries
var stringArray = x.Split(new char[] { ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
//stolen code following
var myEnumerable = stringArray.Skip(2)
.Where((item, index) => index % 4 == 3 || index % 4 == 0)
.Skip(1);
答案 3 :(得分:0)
string[] thestrings = source.Split(',');
string lastItem = thestrings.FirstOrDefault();
List<string> keepers = new List<string>();
foreach(string item in thestrings)
{
if (item == "P")
{
if (lastItem != "P")
{
keepers.Add(lastItem);
}
keepers.Add(item);
}
lastItem = item;
}
答案 4 :(得分:0)
要解析一行,我会使用RegEx代替Linq,因为它编译得更快。