过滤和分割位置

时间:2013-03-28 15:00:12

标签: c# ios linq xamarin

因此我在创建一些共享代码时遇到了我的项目。我有一个包含一些字符串的列表。我想过滤这个,然后将过滤后的字符串拆分到位置。我已经在objective-c中完成了这个,但我无法弄清楚如何在c#中执行此操作。

Objective-c会是这样的:

NSPredicate *findStringWithStatusPlanned = [NSPredicate predicateWithFormat:@"SELF contains[c] 'TOMTOM101'"];
        NSArray *filteredArrayOnStatusPlanned = [trackTraceContentFiltered filteredArrayUsingPredicate:findStringWithStatusPlanned];
        NSLog(@"%@",filteredArrayOnStatusPlanned);

        plannedStatusCompleet = [filteredArrayOnStatusPlanned lastObject];
            janssenRef = [plannedStatusCompleet substringWithRange:NSMakeRange(0, 8)];
            clientRef = [plannedStatusCompleet substringWithRange:NSMakeRange(9, 15)];
            dateReceived = [plannedStatusCompleet substringWithRange:NSMakeRange(25, 10)];
            tomTomCode = [plannedStatusCompleet substringWithRange:NSMakeRange(36, 9)];
            orderText = [plannedStatusCompleet substringWithRange:NSMakeRange(47, 59)];
            podFileName = [plannedStatusCompleet substringWithRange:NSMakeRange(113, 19)];
            Plannedidentifier = [plannedStatusCompleet substringWithRange:NSMakeRange(62, 1)];
            NSLog(@"Planid:%@",Plannedidentifier);

        NSArray *cutContentPlannedStatus = [NSArray arrayWithObjects:janssenRef,clientRef,dateReceived,tomTomCode,orderText,podFileName,Plannedidentifier,nil];
        [[NSUserDefaults standardUserDefaults] setObject:cutContentPlannedStatus forKey:@"plannedData"];

我试着像这样分开:

foreach (string s in TrackTraceDataByLine) {
                string[] splitted = s.Split (new char[] { ' ' });
                if (s.Length >= referenceNumber.Length) {
                    if (referenceNumber == splitted [1]) {
                        dataFilteredOnRef.Add (s);
                    }
                }
            }

我可以很快意识到我必须通过位置来做,而不是分裂空格。这是因为某些部分(如参考编号)可以包含空格。

1 个答案:

答案 0 :(得分:2)

你的意思是这样吗?

var janssenRef = sourceString.Substring(0, 8);
var clientRef = sourceString.Substring(9, 15);
var dateReceived = sourceString.Substring(25, 10);
...
var array = new string[] { ... };

要以Linq样式执行此操作,您可以使用锯齿状数组:

var pos = new int[][] {
    new int[] { 0, 8 }, 
    new int[] { 9, 15 }, 
    new int[] { 25, 10 }, ... };
var array = pos.Select(p => sourceString.Substring(p[0], p[1]))
               .ToArray();

或多维数组:

var pos = new int[,] { { 0, 8 }, { 9, 15 }, { 25, 10 }, ... };
var array = Enumerable.Range(0, pos.GetLength(0))
                      .Select(i => inputString.Substring(pos[i,0], pos[i,1]))
                      .ToArray();