Linq订购输出

时间:2014-04-01 01:41:04

标签: c# linq

我正在尝试按customerID然后按Total (discount*unitPrice*quantity对列表框进行排序,并且无法按照以这种方式对其进行排序的方式来组织代码。任何帮助将不胜感激。

HERE 是一个链接,显示结果应如何返回的图像。

var load1 = System.IO.File.ReadAllLines(@"c:\temp\AS3Products.csv")
            .Select(x => new
            {
                CID = x.Split(',')[0],
                discount = x.Split(',')[2].Trim(),
                productId = x.Split(',')[0].Trim()
            });

var load2 = System.IO.File.ReadAllLines(@"c:\temp\AS3Transactions.csv")
            .Select(x => new
            {
                productId = x.Split(',')[3],
                unitPrice = x.Split(',')[4],
                quantity = x.Split(',')[5]
            });

var querypractice = from x in load1
                    join y in load2 on x.productId equals y.productId 
                    where x.CID == "110"
                    orderby x.discount, y.quantity
                    select new { x.CID, x.discount, x.productId, y.quantity, y.unitPrice };

foreach (var x in querypractice)
{
    double total = double.Parse(x.quantity) * double.Parse(x.unitPrice) * double.Parse(x.discount);
    listBox1.Items.Add(x.CID+ "   " +x.discount+"   "+x.quantity+ "   " + total);
}

2 个答案:

答案 0 :(得分:1)

免责声明:我在这台机器上没有VS,因此未经过验证,但我认为您可以使用LET语句设置计算值,然后根据它进行排序。

var querypractice = from x in load1
                join y in load2 on x.productId equals y.productId 
                let total = x.discount*x.unitPrice*x.quantity
                where x.CID == "110"
                orderby x.CID, total
                select new { x.CID, total };

http://www.codeproject.com/Articles/231164/Into-and-let-in-LINQ-Let-vs-Into

答案 1 :(得分:1)

如果您肯定这些文件始终在预期的位置有数字,您可以在从文件中读取它们时解析它们。否则,您将首先要进行一些验证,否则您将获得例外。

(我已将 double.Parse 更改为 decimal.Parse - it's more accurate for manipulating dollar amounts。)

 var load1 = System.IO.File.ReadAllLines(@"c:\temp\AS3Products.csv")
 .Select(x => new
 {
     CID = int.Parse(x.Split(',')[0]),
     discount = decimal.Parse(x.Split(',')[2].Trim()),
     productId = int.Parse(x.Split(',')[0].Trim())
 });

 var load2 = System.IO.File.ReadAllLines(@"c:\temp\AS3Transactions.csv")
             .Select(x => new
             {
                 productId = int.Parse(x.Split(',')[3]),
                 unitPrice = decimal.Parse(x.Split(',')[4]),
                 quantity = int.Parse(x.Split(',')[5])
             });

然后你可以像这样创建你的列表。 (我删除了您在查询中的特定ID。)

 var orderedList = (from x in load1
                    join y in load2 on x.productId equals y.productId
                    let total = (x.discount * y.unitPrice * y.quantity)
                    orderby x.CID descending, total descending
                    select new
                    {
                        x.CID,
                        x.discount,
                        x.productId,
                        y.quantity,
                        y.unitPrice
                    });