合并两个报告以创建四列单个报告

时间:2013-06-01 05:18:02

标签: c# linq

这与GameBetting相关项目有关。

我们有两个简单的列表。

class Gameresults
{
int userid,
double amount
}

以下两份报告印在纸上。

A) Game Winners
uid       amount
10          -
14          -
15          -

B) Game Losers
uid   amount
11          -
12          -
13          -
16          -

由于此类报告中的列会留下空格 在纸张的宽度,我们必须合并报告和 准备以下报告

Game Winners                           Game Losers
uid   Amount      uid     Amount |   uid   Amount      uid   Amount
10     -          15        -         11     -          13     -
14     -                              12     -          16     -

The above report has two columns for each report.
The Row length of WinnerReport is  totalrecords/2 , therefore two records in first
column and 1 record in next column
So first the right column is filled, rest goes to the left column
Same for LosersReport

Winner vs Losers报告的行长并不重要。 然而,它们必须相等(+/- 1)相对于它们的记录数 各自的名单

我制作了一个Class,将所有记录放在一行,因为我们使用打印机输出报告

class MergeRow
{
    int uidWinCol1; // userid,amount of winner on column 1
    double amtWinCol1;  
    int uidWinCol2;   // userid.amount of winner on column 2
    double amtWinCol2;
    int uidLosCol1;
    double amtLosCol1;
    int uidLosCol2;
    double amtLosCol2;
}

我需要关于如何合并两个列表的部分的建议,我推测这样 一个方法只能在Linq中使用,但任何指针或链接都会有用。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以将winnersList和losersList分成两半。因此,您将有4个子列表。

现在,您可以在每个子列表上使用FirstOrDefault来获取MergeRow的实例。如果其中一个子列表在其他子列表之前变为空,请使用DefaultIfEmpty和占位符项。

代码如下:

        var winnersList = new List<Gameresults>();
        var losersList = new List<Gameresults>();

        //Populate the winnersList and losersList


        var winnersList1 = winnersList.Take(winnersList.Count/2).ToList();
        var winnersList2 = winnersList;
        var losersList1 = losersList.Take(losersList.Count/2).ToList();
        var losersList2 = losersList;

         var allLists = new List<List<Gameresults>> {winnersList1, winnersList2, losersList1, losersList2};
        var mergeRows = new List<MergeRow>();


        while (allLists.Any(l => l.Count > 0))
        {
            var resultsInOneRow = allLists.Select(l => l.DefaultIfEmpty(new Gameresults()).FirstOrDefault()).ToList();
            mergeRows.Add(GetMergeRow(resultsInOneRow));
        }

您的GetMergeRow()方法如下:

        private MergeRow GetMergeRow(List<Gameresults> recordsToMerge)
        {
            var mergeRow = new MergeRow();
            mergeRow.uidWinCol1 = recordsToMerge[0].userid;
            mergeRow.amtWinCol1 = recordsToMerge[0].amount;
            //... and so on
            return mergeRow;
        }