Reputation: 917
I have a list of objects that have a sequence number property (Seq) and an InnerText property (among others). The objects are records (lines) in a text file.
Some records that have InnerText starting with 'X' have one or more continuation records after them that start with 'Y'. I want to add the info in the continuation records to the 'X' record object.
For each 'X' record I need to get a count of the succeeding 'Y' records stopping at the next instance of a non 'Y' record.
I need a way to count the 'Y' records in between the x.Seq record and the next non 'Y' record.
Here is what I have so far with the faulty LINQ statement:
public class File
{
public Queue Records { get; set;}
}
public class Record
{
public int Seq { get; set; }
public string InnerText { get; set; }
}
foreach (Record record in Records)
{
int recSeq = record.Seq;
List<Record> aCopyOfRecords = records;
int numberOfYRecsFollowingX = aCopyOfRecords
.Contains(element =>element.InnerText
.StartsWith("Y") && (element.Seq > recSeq))).Count();
for (int i = (recSeq + 1); i < (recSeq + numberOfYRecsFollowingX); i++)
{
Do Work adding fields etc...
}
}
Thanks in advance for your help
Upvotes: 0
Views: 198
Reputation: 101681
You can use SkipWhile
and TakeWhile
methods
aCopyOfRecords
.SkipWhile(x => x != record)
.Skip(1)
.TakeWhile(x => x.InnerText.StartsWith("Y"));
This will give you the Y
records that comes after specific record that starts with X
.In order to get count, just use Count
.If you want to insert new items to your list, use List<T>.Insert
method:
var count = aCopyOfRecords
.SkipWhile(x => x != record)
.Skip(1)
.TakeWhile(x => x.InnerText.StartsWith("Y"))
.Count();
aCopyOfRecords.Insert(aCopyOfRecords.IndexOf(record) + count, newItem);
Upvotes: 1