遍历数组并使用控制中断逻辑添加元素

Iterate through array and add up elements with a control break logic

我试图在每个循环中使用它来遍历此数组,并在元素 0 相同时对元素 12、10、8、7 和 6 求和 (position.account) , 使用控制中断逻辑,

这是 question I had earlier 的进一步发展,但我似乎无法弄清楚如何从逻辑上做到这一点。

    static void Main(string[] args)
    {
        String path = @"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CsvReader\Position_2016_02_25.0415.csv";

        //Adding lines read into a string[];
        string[] lines = File.ReadAllLines(path);
        foreach(string line in lines)
        {
            Positions position = new Positions();
            string[] parsedLine = line.Split(',');

            position.account = parsedLine[0];
            position.settleMM = parsedLine[10];
            position.open = parsedLine[6];
            position.buy = parsedLine[7];
            position.sell = parsedLine[8];
            position.underlying = parsedLine[12];
            //Need to convert these to an int.

            //for each iteration through the loop where string[0] is already existing
            //I want to have sum = sum + string[10]
        }

        Console.Read();
    }   

    public class Positions
    {
        public string account { get; set; }
        public string symbol { get; set; }
        public string prevClose { get; set; }
        public string curPrx { get; set; }
        public string settlePX { get; set; }
        public string Mult { get; set; }
        public string open { get; set; }
        public string buy { get; set; }
        public string sell { get; set; }
        public string netMM { get; set; }
        public string settleMM { get; set; }
        public string settleDay { get; set; }
        public string underlying { get; set; }
    }

根据我的评论,您可以这样做:

// store the accounts inside this dictionary
var accounts = new Dictionary<string, Positions>();
foreach(string line in lines)
{
    Positions position = new Positions();
    string[] parsedLine = line.Split(',');

    position.account = parsedLine[0];
    ...

    Positions existingAccount;
    // if the account already exists in the dictionary
    if (accounts.TryGetValue(position.account, out existingAccount)) {
        existingAccount.buy += position.buy;
        // do updating logic here
    } else {
        accounts.add(position.account, position);
        // otherwise add it as a new element
    }
}

或者,您可以选择 Linq:

File.ReadLines(path)
    .Select( line => new Position(line) )
    .GroupBy( position => position.account )
    .Select( group => new { Account = group.Key,
                            Sum = group.Select( position => position.settleMM ).Sum() } );