1

I have a text file that contains numbers like this :

84 152 100 52 95 186 169 106 37
86 149 101 56 93 181 171 116 37
84 152 100 52 95 186 169 106 37
86 149 101 56 93 181 171 116 37
84 152 100 52 95 186 169 106 37
86 149 101 56 93 181 171 116 37
84 152 100 52 95 186 169 106 37
86 149 101 56 93 181 171 116 37

Is there a way to read 2 data points like (84,152) and then (100,52)?

string[] lines = File.ReadAllLines(@"C:\Users\Farhan Afzal\Downloads\data_1_2.txt");
string[] line = lines.Select(l => String.Join(" ", l.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))).ToArray();
1
  • Assuming that you have a array of Lines and then each lines contains numbers .for loop with step=2 will do Commented Apr 17, 2013 at 15:09

2 Answers 2

1
var lines = File.ReadAllLines(@"C:\items.txt");
var points = new List<Tuple<int, int>>();
var items = lines.SelectMany(ln => ln.Split(new[] {' '}).Select(n => Convert.ToInt32(n)))
                 .ToList();
for (int i = 0; i < items.Count(); i+=2)
{    
    int second = (i + 1) < items.Count() ? items[ i + 1] : Int32.MinValue;                
    points.Add(Tuple.Create(items[i], second));
}

TODO: error/input format handling

Using MoreLINQ Batch() this will be just

items.Batch(2)
Sign up to request clarification or add additional context in comments.

Comments

0

With the help of side-effect

int dummy = 0;
var result = list.GroupBy(x => dummy++%2)
                .Select(g => g.ToArray())
                .ToList();

And a long version without side effect

var result = list.Select((x,i)=>new {item=x,index=i})
                .GroupBy(x => x.index%2)
                .Select(g => g.Select(x=>x.item).ToArray())
                .ToList();

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.