簡體   English   中英

如何組合列表的元素

[英]How to combine elements of a list

我在c#工作。 我有一個排序的結構列表。 該結構具有一個存儲月份和年份的DateTime對象以及一個存儲值的整數。 該列表按日期排序。 我需要遍歷列表並將其組合起來,以便每個日期只有一個結構實例。

例如:我的初始列表如下所示:

{ (Apr10, 3), (Apr10, 2), (Apr10, -3), (May10, 1), (May10, 1), (May10, -3), (Jun10, 3) } 

結果列表應如下所示:

{ (Apr10, 2), (May10, -1), (Jun10, 3) }

我正在尋找一個簡單/有效的解決方案。

結構是:

struct CurrentTrade
{
    public DateTime date;
    public int dwBuy;
}

清單是:

private List<CurrentTrade> FillList

您可以使用LINQ:

var newList = (
    from trade in FillList
    group trade by trade.Date.Date into g
    select new CurrentTrade { date = g.Key, dwBuy = g.Sum(t => t.dwBuy) }
).ToList();

如果您不想使用LINQ:

如果列表按日期排序,則具有相同日期的所有項目彼此相鄰。 你可以這樣做:

for ( int i = FillList.Count - 1; i >= 1; i-- ) {
    if ( FillList[i].date == FillList[i-1].date ) {
       FillList[i-1].dwBuy += FillList[i].dwBuy;
       FillList.RemoveElementAt( i );
    }
}

如果您的.NET支持,建議使用LINQ解決方案。

如果輸入日期包含時間組件並且您想要在日期上合並,只需更改if語句:

if ( FillList[i].date == FillList[i-1].date )

if ( FillList[i].date.Date == FillList[i-1].date.Date )

看看LINQ語句

var result  = FillList.GroupBy(x => x.date)
                      .Select(g => new CurrentTrade { 
                          date = g.Key, 
                          dwBuy = g.Sum(x => x.dwBuy) 
                      })
                      .ToList();

編輯:

如果CurrentTrade確實包含時間組件,則應將其轉換為僅日期DateTime對象:

var result  = FillList.GroupBy(x => x.date.Date)
                      .Select(g => new CurrentTrade { 
                          date = g.Key, 
                          dwBuy = g.Sum(x => x.dwBuy) 
                      })
                      .ToList();

那么使用HashSet<T>呢? HashSet不能包含兩次相同的對象。 但是,這可能需要您在CurrentTrade類中重新實現GetHash方法。

(像return Date.GetHashCode() ^ dwBug這樣的事情可以做到。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM