选择已经声明的列表

时间:2013-10-30 00:50:15

标签: c# .net c#-4.0 lambda

我有一段代码,它从列表和内部选择中进行选择,它实例化其他列表并将自然数据复制到其中。

var rep = Histories.Select(rec => new ReportRecord()
                            {
                                Name = rec.ProductName,
                                Total = rec.AdvanceTotal,
                                BidTotal = rec.LiveTotal

                            });

我需要修改此代码(由于Lambda技能有限,我无法修改),以便在select之前实例化var rep。类似的东西:

 var rep = new ReportRecord();
 Histories.Select(c => rep.ProductName=c.Name,
 rep.Total=c.AdvanceTotal,
 rep.BidTotal=rec.LiveTotal);

你能帮我解决正确的syntex吗?

我非常赞赏你的帮助和指导。

由于

2 个答案:

答案 0 :(得分:1)

你的问题相当不明确。如果你澄清一点,那么我们将能够更好地回答你的问题。

但我认为您想要的是ReportRecord的单个实例,其中包含来自Histories的数据。

var rep = Histories.Select(rec => new ReportRecord()
                            {
                                ProductName = rec.Name,
                                Total = rec.AdvanceTotal,
                                BidTotal = rec.LiveTotal

                            }).First();

这将从Histories获取第一条记录,然后使用该行值填充新的ReportRecord

var是占位符类型。它可以是任何东西。编译器可以解决它应该是什么。 但是,如果您知道它是什么,我个人会发现更清楚。 像这样:

ReportRecord rep = Histories.Select(rec => new ReportRecord()
                            {
                                ProductName = rec.Name,
                                Total = rec.AdvanceTotal,
                                BidTotal = rec.LiveTotal

                            }).First();

我给出的解决方案将为您提供Histories的第一行,如果您想要最后一行,那么您将.First();替换为.Last();

更多信息:

在原始代码示例中,您获得了IEnumerable<ReportRecord>(或者可能是IQuerable)这是ReportRecords的集合,在您尝试从中提取值之前,它不会被填充。例如,通过调用First(),ToList(),Sum()。

还有其他一些你可以执行的操作,比如过滤,直到你在调用First()之类的东西之后才会使用.Where()直到列表向下运行,例如。

//Get the first record from Histories where the product name is "Magic beans" and populate a new ReportRecord with those values
ReportRecord rep = Histories.Select(rec => new ReportRecord()
                            {
                                ProductName = rec.Name,
                                Total = rec.AdvanceTotal,
                                BidTotal = rec.LiveTotal

                            }).Where(w => w.Name == "magic beans")
                              .First();

以下是其他LINQ扩展方法http://www.nilzorblog.com/2013/05/101-linq-samples-lambda-style.html

的一些示例

答案 1 :(得分:0)

您正在调用的Select()方法可能会返回IEnumerable<ReportRecord>而不是单个值。在您的解决方法中,您使用的是单个值。这可能让你感到困惑。

相关问题