Linq To Text Files

I have a text file (sorry, I am not allowed to work with XML files :(), and it includes client entries. Each text file looks like this:

Account_ID: 98734BLAH9873
User Name: something_85
First Name: ILove
Last Name: XML
Age: 209

etc. And I need to be able to use LINQ to get data from these text files and just store them in memory.

I saw a lot of Linq for SQL, Linq for BLAH, but nothing for Linq to Text. Can someone please help me out?

thank

+3
source share
4 answers

You can use this code

var pairs = File.ReadAllLines("filename.txt")
    .Select(line => line.Split(':'))
    .ToDictionary(cells => cells[0].Trim(), cells => cells[1].Trim())

Or use the .NET 4.0 File.ReadLines () method to return IEnumerable, which is useful for handling large text files.

+12

(, XML ). , .

Account, LINQ-to-Objects.

+6

Filehelpers - :

http://filehelpers.sourceforge.net/

, FileHelpers :

[FixedLengthRecord]
public class PriceRecord
{
    [FieldFixedLength(6)]
    public int ProductId;

    [FieldFixedLength(8)]
    [FieldConverter(typeof(MoneyConverter))]
    public decimal PriceList;

    [FieldFixedLength(8)]
    [FieldConverter(typeof(MoneyConverter))]
    public decimal PriceOnePay;
}

FileHelpers , Linq

. , Kaerber - , , FileHelpers, .

+5

; , , . , .

. , :

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;

namespace LinqToText
{
  public static class StreamReaderSequence
  {
    public static IEnumerable<string> Lines(this StreamReader source)
    {
      String line;

      if (source == null)
          throw new ArgumentNullException("source");
      while ((line = source.ReadLine()) != null)
      {
        yield return line;
      }
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      StreamReader sr = new StreamReader("TextFile.txt");

      var t1 =
        from line in sr.Lines()
        let items = line.Split(',')
        where ! line.StartsWith("#")
        select String.Format("{0}{1}{2}",
            items[1].PadRight(16),
            items[2].PadRight(16),
            items[3].PadRight(16));

      var t2 =
        from line in t1
        select line.ToUpper();

      foreach (var t in t2)
        Console.WriteLine(t);

      sr.Close();
    }
  }
}

:

#This is a comment
1,Eric,White,Writer
2,Bob,Jones,Programmer
3,Orville,Wright,Inventor
4,Thomas,Jefferson,Statesman
5,George,Washington,President

.

ERIC            WHITE           WRITER
BOB             JONES           PROGRAMMER
ORVILLE         WRIGHT          INVENTOR
THOMAS          JEFFERSON       STATESMAN
GEORGE          WASHINGTON      PRESIDENT
+2

Source: https://habr.com/ru/post/1742958/


All Articles