1

I have created a below text file

AB12345 werwer ssd fghfh
BA12345 wewewe wer sdfsf
CD44444 werwe werwe dgdg
DC44444 dsgdgfd dfgg fdgdfg

I want to read the lines & create lists based on matching values at position start from 2 to 6 i.e 12345 which is present in two rows. So it will create list a below

**List 1**                   **List 2**
AB12345 werwer ssd fghfh     CD44444 werwe werwe dgdg
BA12345 wewewe wer sdfsf     DC44444 dsgdgfd dfgg fdgdfg

Please let me know how to achieve this using linq.

1
  • are these values will remain static? Jun 6, 2014 at 12:07

2 Answers 2

0

Just group lines by substring from 2 to 6:

var lists = from l in File.ReadLines("fileName")
            group l by l.Substring(2,4) into g
            select g.ToList();

Lambda syntax:

var lists = File.ReadLines("fileName")
                .GroupBy(l => l.Substring(2,4))
                .Select(g => g.ToList());

Output:

[
  [ "AB12345 werwer ssd fghfh", "BA12345 wewewe wer sdfsf" ],
  [ "CD44444 werwe werwe dgdg", "DC44444 dsgdgfd dfgg fdgdfg" ]
]

Note you can select group directly, without converting it to list. In that case you will have also information about grouping key of each group, i.e. "1234" and "4444" in your case. E.g.

var groups = File.ReadLines("fileName").GroupBy(l => l.Substring(2,4));

Or even you can use lookup:

var lookup = File.ReadLines("fileName").ToLookup(l => l.Substring(2,4));

That will allow you easily access list of lines by their key:

IEnumerable<string> list1 = lookup["1234"];
IEnumerable<string> list2 = lookup["4444"];
0

Do a projection using Select to retrieve the desired part of the line thanks to a string.SubString (i.e. 12345 or 44444) then apply a GroupBy on that value to split the input list.

Basically something like (not actually tested):

var results = inputList
    .Select(z => new
    {
        Match = z.Substring(2, 5),
        Value = z
    })
    .GroupBy(z => z.Match);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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