(应该很简单)LINQ问题 [英] (Should be really simple) LINQ question
问题描述
根据我的书,我以为我理解LINQ。我没有。
我想做的就是加一些数字。我的代码如下。不编译的位是显而易见的。
我的问题是我做错了什么?我想做的就是将数字加1 + 2 + 5 - 1000 + 100 = -892,但我甚至不能这样做。
请有人帮帮我。
谢谢
Hi, I thought I understood LINQ according to my book. I don't.
All I want to do is sum some numbers. My code is below. The bit that doesn't compile is obvious.
My question is what am I doing wrong? All I want to do is sum the numbers 1 + 2 + 5 - 1000 + 100 = -892 but I can't even do that.
Please please can someone help me out here.
Thank you
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication7
{
class C3
{
public C3(int foo) { Foo = foo; }
public int Foo { get; set; }
}
class C2
{
public C2(List<C3> bar) { Bar = bar; }
public List<C3> Bar { get; set; }
}
class C1
{
public C1(List<C2> baz) { Baz = baz; }
public List<C2> Baz { get; set; }
}
class Program
{
public void Run()
{
C2 c2_1 = new C2(new List<C3> {new C3(1), new C3(2), new C3(5)});
C2 c2_2 = new C2(new List<C3> { new C3(-1000), new C3(100) });
C1 c1 = new C1(new List<C2>() { c2_1, c2_2 });
//Answer = -892, but I can't even get the syntax right for it to compile
var resultSum = c1.Baz.Select(x => x.Bar).Sum(y => y.Foo);
}
static void Main(String[] args)
{
new Program().Run();
}
}
}
推荐答案
我认为Baz.Select返回列表列表, NL。 Bar的列表(这是一个列表)ants lsit没有属性Foo
你试过SelectMany吗?
I think Baz.Select returns a list of lists, nl. a list of Bar (which is a list) ant the lsit does not have property Foo
Have you tried SelectMany ?
嗨Serge,是的我也试过SelectMany ,代码如下:
Hi Serge, yes I tried SelectMany too, code below:
var resultSum = c1.Baz.Select(x => x.Bar).SelectMany(y => y.Foo).Sum(z => z);
我无法得到这个虽然我认为语法是正确的,但它显然不是。
I cant get this to compile either so although I think the syntax is correct, it clearly is not.
你可以这样做:
you can do it like that:
var resultSum = c1.Baz.SelectMany(x => // selecting all Bars as one IEnumerable
x.Bar).Sum(x => // summing all Foos.
x.Foo);
ps:请发表评论作为评论,不是解决方案。
ps: please send your comment as comment, not a solution.
这篇关于(应该很简单)LINQ问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!