我有一个字符串,在交替的行中有两种不同类型的数据(,即两行创建一个记录)。我想只选择那些长度为2(即偶行)小于1000的记录。
我试过这个但是它导致只选择偶数 th 行并丢弃奇数行:
var lessthan1000Length = recordsFile.Where((src, index) => src.Length<1000 && index%2 != 0);
来自recordsFile的示例数据
2012-12-04 | 10:45 AM | Lahore
Added H2SO4 in the solution. Kept it in the lab temperature for 10 minutes
2012-12-04 | 10:55 AM | Lahore
Observed the pH of the solution.
2012-12-04 | 11:20 AM | Lahore
Neutralized the solution to maintain the pH in 6-8 range
感谢您的指导。
P.S:请注意,结果必须采用List<string>
的形式,因为我们必须从中制作新的数据集。
答案 0 :(得分:3)
var odds = recordsFile.Where((str, index) => index % 2 == 0);
var evens = recordsFile.Where((str, index) => index % 2 == 1);
var records = odds.Zip(evens, (odd, even) => new { odd, even })
.Where(pair => pair.even.Length < 1000);
foreach (var record in records)
Console.WriteLine(record);
答案 1 :(得分:2)
List<string> result = recordFile
.Select( (str, index) => new {str, index})
.GroupBy(x => x.index / 2, x => x.str)
.Where(g => g.Last().Length < 1000)
.Select(g => g.First() + g.Last())
.ToList();
答案 2 :(得分:1)
如果您使用Microsoft的Reactive Framework团队的“Interactive Extensions”,您将获得一个可以帮助您的好的扩展方法。
$ gdb a.out
[...]
(gdb) run
[...]
all well?: 5
all well?: 234
all well?: 9
all well?: 79
all well?: 26
all well?: 108
all well?: 21
all well?: 195
all well?: 192
all well?: 148
all well?: 64
all well?: 211
all well?: 245
all well?: 90
all well?: 173
all well?: 238
all well?: 167
all well?: 125
all well?: 14
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a9ec82 in free () from /lib64/libc.so.6
(gdb) bt
#0 0x00007ffff7a9ec82 in free () from /lib64/libc.so.6
#1 0x00007ffff7a96856 in __underflow () from /lib64/libc.so.6
#2 0x00007ffff7a945a8 in __GI__IO_file_xsgetn () from /lib64/libc.so.6
#3 0x00007ffff7a898e6 in fread () from /lib64/libc.so.6
#4 0x0000000000400b69 in myFunction ()
at FileName.c:88
#5 0x0000000000400ebc in main (argc=1, argv=0x7fffffffdfd8)
at FileName.c:173
根据您的示例数据,我得到了这个:
只需NuGet“Ix-Main”来获取扩展方法 - 除了var query =
from pair in lines.Buffer(2)
where pair[1].Length < 1000
select pair;
var results = query.ToList();
之外还有很多其他方法,其中很多都非常有用。
答案 3 :(得分:1)
亚历山大的回答似乎很好。
或者,您可以创建一种方法将序列(具有偶数个项)转换为一对序列。我猜是这样的:
.Buffer
您可以static IEnumerable<Tuple<T, T>> PairUp<T>(this IEnumerable<T> src)
{
using (var e = src.GetEnumerator)
{
while (e.MoveNext())
{
var first = e.Current;
if (!e.MoveNext())
throw new InvalidOperationException("Count of source must be even"); // OR: yield break; OR yield return Tuple.Create(first, default(T)); yield break;
var second = e.Current;
yield return Tuple.Create(first, second);
}
}
}
或类似。
编辑:由于您希望将两个“部分”连接为字符串,因此recordsFile.PairUp().Where(t => t.Item2.Length < 1000)
。