1

The below is a CSV string I am working with. Its much bigger in reality but this is enough to display a pattern.

Please note that I have put this CSV on seperate lines just to demonstrate my pattern easily.

After a CSV split the number of fields are variable depending on how big the original string is i.e. the string is a variable length which makes the number of indexes variable

The letter in the pattern may not always be P, it could be U, O or 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,

I want to pick up the 5th (29) and 6th (P) elements and then miss 2 elements and then pick the next element (07) and the one after (P) and so on until I get to the end of the string.

In this example I will have 29 P 07 P 08 P 07 P

Is there an easy way to do this, I assume LINQ will offer something

Thanks

5
  • You don't say why you want those elements. I'm guessing the rule is 'all elements that are either P or followed by a P', but that's only a guess. What happens if the first element is P ?
    – AakashM
    Commented Nov 3, 2011 at 14:59
  • is that CSV? or is each value on a new line? Note: LINQ is not a magic bullet to solve every problem - if the data is as it appears, then File.ReadAllLines or StreamReader should help. Commented Nov 3, 2011 at 14:59
  • 1
    Apologies it is a CSV, I thought putting it on a new line might demonstrate my example better. I can change it back to CSV if you prefer
    – Jon
    Commented Nov 3, 2011 at 15:01
  • @Jon: thanks for that, good choice; however, a comment would have been in order to make it obvious. Will you edit the question accordingly?
    – sehe
    Commented Nov 3, 2011 at 15:06
  • Question updated with bold font
    – Jon
    Commented Nov 3, 2011 at 15:12

5 Answers 5

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

But this doesn't at all seem descriptive of what the code is doing, I'd at least put a comment.

2
  • Can you please comment it for my unworthy eyes because I dont get it!
    – Jon
    Commented Nov 3, 2011 at 15:13
  • it's not actually about lines... the OP has clarified
    – sehe
    Commented Nov 3, 2011 at 15:14
2

A full demo on http://ideone.com/EDof0

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()));
    }
}

Output:

29 P 07 P 08 P 07 P

10
  • I'm getting pretty certain I must have been hell-banned. None of my answers are getting any attention lately :(
    – sehe
    Commented Nov 3, 2011 at 15:18
  • to be fair, I really don't like that static 100 for the range. I might have gone with Enumerable.Range(1, int.MaxValue - 1).SelectMany(...).TakeWhile(i => i is not outside string length) Commented Nov 3, 2011 at 15:22
  • @YuriyFaktorovich: I'm pretty positive you haven't tried that
    – sehe
    Commented Nov 3, 2011 at 15:23
  • I've used something like it in the past. Commented Nov 3, 2011 at 15:24
  • Could you not do the csvString split first and then the Enumberable.Range becomes Enumerable.Range(1,fields.length)
    – Jon
    Commented Nov 3, 2011 at 15:30
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;
}
0

i've done something like this yesterday... here's my code

//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);
2
  • This is similar to Yuriy's answer. Can you explain whats going on. I dont quite understand the mod stuff and not to complain but that isnt working on my CSV
    – Jon
    Commented Nov 3, 2011 at 15:11
  • explained it... sry i have wrote ';' in the split instead of ',' because in my program is used ';' :p sorry for that... hoping for an up ;)
    – kyjan
    Commented Nov 3, 2011 at 15:25
0

To parse a row I would use a RegEx instead Linq as it is compiled and much faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.