Trupti Pandit Samant
Trupti Pandit Samant

Reputation: 81

Can I write a LINQ query to parse string

I have a string like this:

A00601  CALLE FCO PIETRI   CALLE FRANCISCO PIETRI            A20040407

Is there a way to replace this code:

foreach (var line in parsedList)
{
     if((line[0] == 'D') && (line[55] == 'Y'))
     {
         item.PostalCode5 = line.Substring(1, 5);
         item.PreferredCityName28 = line.Substring(13,28);
          ...
      }
 }

With a LINQ query like this:

foreach (var line in parsedList)
{
     item.PostalCode5(line.Substring(1, 5)),
     item.PreferredCityName28(line.Substring(13,28))
     ...
     .Where (line[0] == 'D' &&  line[55] == 'Y')
 }

Upvotes: 0

Views: 81

Answers (2)

Lux
Lux

Reputation: 18240

You can do this:

parsedList.Where(line => line[0]== 'D' && line[55] = 'Y')
  .ToList()
  .ForEach(line => {
    item.PostalCode5(line.Substring(1, 5)),
    item.PreferredCityName28(line.Substring(13,28))
  });

Which is identical to your code.

Upvotes: 1

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

parsedList
    .Where(line => line[0]== 'D' && line[55] = 'Y')
    .Select(itm => new Item {
        PostalCode5 = line.Substring(1, 5), 
        PreferredCityName28 = line.Substring(13,28)
    });

Upvotes: 2

Related Questions