3

仕訳入力項目を含む入力ファイル (CSV) を取得し、仕訳入力ごとに処理する必要があります。ジャーナル エントリは、データベースと日付の個別のグループごとに定義されます。

サンプル CSV データ:

LineNo,Database,Date,Amount
1,DB3,03/12/2013,1.00
2,DB1,10/14/2013,1.00
3,DB2,08/12/2013,1.00
4,DB3,03/12/2013,1.00
5,DB2,08/12/2013,1.00
6,DB1,10/14/2013,1.00
7,DB1,08/12/2013,1.00
8,DB1,08/12/2013,1.00

グループの例は上記の 7 行目と 8 行目です。これらは異なるデータベースに属し、異なる日付を持っているからです。3行目と5行目も同様。

CSV 内の行が特別な順序で提供されていない場合、一度に 1 つずつループして各仕訳エントリを調べる最も効果的/効率的なコードは何ですか? 特定の日誌エントリの各フィールドと各レコードを参照できる必要があります。

以下に CSV の読み取りに成功した最初の試みを含めましたが、ジャーナル エントリごとに読んでいるのではなく、1 行ずつ調べていることを十分に認識しています。これはあまり役に立ちません。

可能であれば、この問題を解決するためのより優れた強力な手法を学びたいです。

public static void SeparateJournalEntries()
{
   string UploadFilePath = @"\\server\folder\upload.csv";  
   var reader = new StreamReader(File.OpenRead(UploadFilePath));
   string previousSite = "";
   int JEcounter = -1;
   int lineNumber = 1;

   while (!reader.EndOfStream)
   {
      var line = reader.ReadLine();
      string[] fields = line.Split(',');
      Console.WriteLine(fields[0].ToString() + " " + fields[1].ToString());

      JEfields JEinstance = new JEfields
      {
         Database = fields[0],
         Date = fields[1],
         Amount = fields[2]
      };

      if (JEinstance.Site == previousSite || previousSite == System.String.Empty & lineNumber > 1)
      {
         JEcounter += 1;
         previousSite = JEinstance.Site;
      }

   }

}
4

3 に答える 3

1

この問題を解決するには、Linq とオブジェクトの力を利用します。単一の Linq ステートメントを使用して、ファイルを読み込んで並べ替えることができます。次に、Journal オブジェクトを目的の順序でループしたり、簡単に並べ替えたりできます。

ファイルを読み込んで並べ替えるには:

    private void button4_Click(object sender, EventArgs e)
    {
        IEnumerable<Journal> sortedJournals = GetJournals(@"c:\temp\test.txt");

        //now you can loop through sortedJournals

        //or you can create groups of journals
        var journalByDatabase = sortedJournals.ToLookup(j => j.Database + j.Date);

        foreach (var group in journalByDatabase)
        {
            foreach (var item in group)
            {
            }
        }
    }

    public IEnumerable<Journal> GetJournals(string JournalsPath)
    {

        var myJournals =
            from c in
                (
                    from line in File.ReadAllLines(JournalsPath).Skip(1)
                    let aRecord = line.Split(',')
                    select new Journal()
                    {
                        LineNo = Convert.ToInt32(aRecord[0].Trim()),
                        Database = aRecord[1].Trim(),
                        Date = Convert.ToDateTime(aRecord[2].Trim()),
                        Amount = Convert.ToDecimal(aRecord[3].Trim()),
                    }
                ).OrderBy(x => x.Database)
            select c;

        return myJournals;

    }

単純なジャーナル クラス:

public class Journal
{
    public int LineNo { get ;set;}
    public string Database { get; set;}
    public DateTime Date { get; set; }
    public Decimal Amount { get; set; }

    public Journal()
    {
    }
}
于 2013-10-08T22:48:03.263 に答える
1

実際に必要なのは、これらの値をを使用して定義された一意のキー{DbName,Date}でグループ化し、各キーからエントリのリストへのマッピングを作成することです。

何よりもまず、この一意のキーを表すクラスを作成し、IEquatable<T>インターフェイスを実装する必要があります。Equalsこれにより、同じデータベース名と日付を持つ 2 つの異なるインスタンスでメソッドを呼び出すと、確実にが返さtrueれ、.NET マッピング構造が適切に機能するために必要になります。

/// <summary>
/// Represents a unique journal info.
/// This class implements value-type comparison semantics.
/// </summary>
class JournalInfo : IEquatable<JournalInfo>
{
    private readonly string _dbName;
    /// <summary>Gets the database name.</summary>
    public string DbName
    { get { return _dbName; } }

    private readonly DateTime _date;
    /// <summary>Gets the date.</summary>
    public DateTime Date
    { get { return _date; } }

    /// <summary>Initializes a new instance of the <see cref="JournalInfo"/> class.</summary>
    public JournalInfo(string db, DateTime date)
    {
        _dbName = db; _date = date;
    }

    #region Equals overrides to ensure value-type comparison semantics

    // a lot of plumbing needs to be done here to solve a simple task,
    // but it must be done to ensure consistency in all cases

    /// <summary>Determines whether the specified <see cref="JournalInfo" /> is equal to this instance.</summary>
    public bool Equals(JournalInfo other)
    {
        if (object.ReferenceEquals(other, null)) 
            return false;
        else 
            return this.DbName == other.DbName && this.Date == other.Date;
    }

    /// <summary>Determines whether the specified <see cref="System.Object" /> is equal to this instance.</summary>
    public override bool Equals(object other)
    {
        return this.Equals(other as JournalInfo);
    }

    /// <summary>Returns a hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</summary>
    public override int GetHashCode()
    {
        var hash = 17;
        if (this.DbName != null) hash += this.DbName.GetHashCode();
        hash = hash * 31 + this.Date.GetHashCode();
        return hash;
    }

    public static bool operator ==(JournalInfo a, JournalInfo b)
    {
        if (object.ReferenceEquals(a, null))
            return object.ReferenceEquals(b, null);

        return ((JournalInfo)a).Equals(b);
    }

    public static bool operator !=(JournalInfo a, JournalInfo b)
    {
        if (object.ReferenceEquals(a, null))
            return !object.ReferenceEquals(b, null);

        return !((JournalInfo)a).Equals(b);
    }

    #endregion
}

このクラスの準備ができたので、それを使用してJournalEntryクラスを作成できます。

class JournalEntry
{
    public int LineNumber { get; set; }
    public JournalInfo Info { get; set; }
    public Decimal Amount { get; set; }
}

これで、LINQ を使用してこれらの値をグループ化し、エントリのリストにマップできるようになりました。

var path = "input.txt";
var culture = System.Globalization.CultureInfo.InvariantCulture;

Dictionary<JournalInfo, List<JournalEntry>> map = 
    File.ReadLines(path) // lazy read one line at a time
        .Skip(1) // skip header
        .Select(line => line.Split(',')) // split into columns
        .Select((columns, lineNumber) => new JournalEntry() 
            {   // parse each line into a journal entry
                LineNumber = lineNumber,
                Info = new JournalInfo(
                    columns[1], 
                    DateTime.ParseExact(columns[2], "MM/dd/yyyy", culture)),

                Amount = decimal.Parse(columns[3], culture)
            })
        .GroupBy(entry => entry.Info) // group by unique key
        .ToDictionary(grouping => grouping.Key, grouping => grouping.ToList()); 

これで、ループを使用してこれをコンソールにダンプできます。

// this loop also orders entries by database name and date
foreach (var item in map.OrderBy(m => m.Key.DbName).ThenBy(m => m.Key.Date))
{
    Console.WriteLine("Journal: {0} - {1:dd/MM/yyyy}", 
        item.Key.DbName, 
        item.Key.Date);

    foreach (var entry in item.Value.OrderBy(e => e.LineNumber))
    {
        Console.WriteLine(" - Line {0}, Amount = {1:0.00}",
            entry.LineNumber,
            entry.Amount);
    }
}

入力ファイルの場合、このコードは次を出力する必要があります。

Journal: DB1 - 12.08.2013
 - Line 6, Amount = 1,00
 - Line 7, Amount = 1,00
Journal: DB1 - 14.10.2013
 - Line 1, Amount = 1,00
 - Line 5, Amount = 1,00
Journal: DB2 - 12.08.2013
 - Line 2, Amount = 1,00
 - Line 4, Amount = 1,00
Journal: DB3 - 12.03.2013
 - Line 0, Amount = 1,00
 - Line 3, Amount = 1,00
于 2013-10-10T09:43:04.867 に答える