【问题标题】:selecting to a list which is already declared选择已声明的列表
【发布时间】:2013-10-30 00:50:14
【问题描述】:

我有下面的一段代码,它是从一个列表中选择的,在选择中它会实例化其他列表并将获取的数据复制到其中。

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

                            });

我需要修改此代码(由于 Lambda 技能有限,我无法修改),以便在选择之前实例化 var rep。比如:

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

你能帮我正确的语法吗?

非常感谢您的帮助和指导。

谢谢

【问题讨论】:

  • @Toubi,你的问题对我来说毫无意义。请详细说明您实际尝试解决的具体问题,而不是请求可能适用于或不适用于您的问题的特定语言习语。
  • rep 的类型在你的两个例子中是不同的,在第一个例子中它是 IEnumerable<ReportRecord> 在第二个例子中它只是 ReportRecord,你需要像柯克说的那样做并解释更多关于你正在尝试做的事情,而不是问如何做你认为可能有效的解决方案来做你想做的事情。这被称为the XY Problem

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


【解决方案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 的第一行,如果你想要最后一行,那么你可以用.Last(); 替换.First();

更多信息:

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

您还可以执行其他操作,例如过滤,直到使用 .Where() 才能在列表中运行,直到您调用 First() 或类似的东西才会实际调用,例如,

//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 的一些示例

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多