如何遍历System.Collections.Generic.List`1

我无法从Google搜索中获得明确的指导。我有一个名为的表transaction,我想针对外键进行分组BatchID和排序descending。


表定义


[TTransactionID]      INT          IDENTITY (1, 1) NOT NULL,

[BatchID]             INT          NULL,

[CardID]              INT          NULL,

[UserID]              INT          NULL,

[TransactionDateTime] DATETIME     NOT NULL,

[TransactionStatus]   VARCHAR (11) NOT NULL,

CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED ([TTransactionID] ASC),

CONSTRAINT [FK_Transactions_Cards] FOREIGN KEY ([CardID]) REFERENCES [dbo].[Cards] ([CardID]),

CONSTRAINT [FK_Transactions_Users] FOREIGN KEY ([UserID]) REFERENCES [dbo].[Users] ([UserID]) NOT FOR REPLICATION

这是我第五次尝试的代码


        var TransactionList = db.Transactions

                                .GroupBy(x => new { x.BatchID })

                                .Select(x => x.ToList()).ToList();


        int index = 0;

        foreach (var item in TransactionList)

        {

            Response.Write( string.Format("[{0}] - {1}", index, item) );

            index++;

        }

当我运行上面的代码时。我在浏览器上收到以下消息。我被困在这里,之后我不知道该怎么办。


System.Collections.Generic.List`1[SECardDistribution.Models.Transaction]

请告知谢谢


鸿蒙传说
浏览 821回答 3
3回答

一只名叫tom的猫

请注意,TransationList按BatchId升序排序,然后按CardId降序排序。var TransactionList = context.Trx                .GroupBy(t => t.BatchId)    //group by BatchId                .OrderBy(t => t.Key)        //order by BatchId                .Select                (g =>                    //Create a new "Batch Group" anonymously where each batch contains the associated transactions                    new                    {                        BatchId = g.Key,                        BatchTransactions = g.Select(trx => new { Card = trx.Card, User = trx.User }).OrderByDescending(batchTrx => batchTrx.Card.CardId),    //order by CardId                    }                );要遍历排序列表,可以使用嵌套的foreach循环,如下所示://Loop through the batch group in the sorted list            foreach(var batchGroup in TransactionList)            {                foreach(var batchTrx in batchGroup.BatchTransactions)                {                    //You may access the properties of batchTrx like a normal object graph, example batchTrx.Card.CardId                }            }

海绵宝宝撒

你可以SelectMany实际使用var transactionList = db.Transactions.GroupBy(x => new { x.BatchID }).SelectMany(x => x).ToList();

慕侠2389804

// doing Select(x => x.ToList()) throws away group key!var TransactionList = db.Transactions.GroupBy(x => x.BatchID).ToList();foreach (var group in TransactionList){    // now group variable is a ... well, group of transactions. :)    // you can get its key and iterate over sub-collection of transactions in this group.    Response.Write($"Group {group.Key}:\n");    foreach (var item in group)    {        Response.Write($"    Transaction {item.TTransactionID}\n");    }}
打开App,查看更多内容
随时随地看视频慕课网APP