C# Linq排序输出
我试图按C# Linq排序输出,c#,linq,C#,Linq,我试图按客户ID对列表框进行排序,然后再按总计(折扣*单价*数量)对列表框进行排序,但无法以这样的方式组织代码。任何帮助都将不胜感激 是一个链接,显示有关结果应如何返回的图像 var load1 = System.IO.File.ReadAllLines(@"c:\temp\AS3Products.csv") .Select(x => new { CID = x.Split(',')[0],
客户ID
对列表框进行排序,然后再按总计(折扣*单价*数量
)对列表框进行排序,但无法以这样的方式组织代码。任何帮助都将不胜感激
是一个链接,显示有关结果应如何返回的图像
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);
}
免责声明:我在这台机器上没有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 };
如果您确信这些文件始终在预期的位置上有数字,您可以在从文件中读取数字时对其进行解析。否则,您需要先进行一些验证,否则会出现异常
(我将double.Parse
更改为decimal.Parse
-)
然后你可以像这样创建你的列表。(我删除了查询中的特定id。)
您是否尝试过实现自定义的
IComparer
?谢谢,这正是我一直试图找出的代码,使用让
创建总计就是我所需的准确信息。太好了-如果成功,请标记为正确答案,或者让我知道任何编译问题,我会更新答案。见下面格兰特的答案-我忘了将项目转换为数字类型。您需要这样做才能使用*运算符。
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])
});
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
});