Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从foreach中编辑属性不会影响集合_C#_Grouping - Fatal编程技术网

C# 从foreach中编辑属性不会影响集合

C# 从foreach中编辑属性不会影响集合,c#,grouping,C#,Grouping,我编写了一个测试用例: 我有一张这样的桌子 Id|IdA|IdW|Quantity 1 1 3 5 2 1 4 2 3 2 5 3 Id是主键,IdA是物品Id,IdW是箱子Id,数量是物品数量 现在,我必须按IdA对数量求和进行分组,所以我要做: var groups = models .GroupBy(x => new { x.IdA }) .Select (

我编写了一个测试用例:

我有一张这样的桌子

Id|IdA|IdW|Quantity
1  1   3    5
2  1   4    2
3  2   5    3
Id
是主键,
IdA
是物品Id,
IdW
是箱子Id,数量是物品数量

现在,我必须按
IdA
对数量求和进行分组,所以我要做:

var groups = 
        models
            .GroupBy(x => new { x.IdA })
            .Select
            (
                x => 
                    new Model
                    { 
                        Id = (x.Select(y => y.Id).Count() > 1) ? 0 : x.Select(y => y.Id).First(), 
                        IdA = x.Key.IdA, 
                        Qty = x.Sum(y => y.Qty) 
                    }
            );
上表显示了
型号
。它工作得很好,在没有进行分组时,我还设法保留了主键(只有一个
IdA

现在我想这样做:我想为那些没有分组的保留
IdW
。理想的结果是:

Id|IdA|IdW|Quantity
0  1   0    7
3  2   5    3
我尝试对组执行foreach,使用主键检索行,然后将
IdW
设置为组,如下所示:

foreach(var e in groups)
{
    var nonGroupedRow = models.Where(x => e.Id != 0 && x.Id == e.Id).FirstOrDefault();
    var targetModel = groups.FirstOrDefault(x => x.Id == e.Id);
    if(nonGroupedRow != null && targetModel != null)
    {
        targetModel.IdW = nonGroupedRow.IdW;
    }
}
这根本不起作用。两组仍有
IdW=0
。我还做了另一个测试,做:

void Main()
{
    var a = new List<A> { new A { Id = 1 }, new A { Id = 2 } };
    a.FirstOrDefault(x => x.Id == 1).Id = 2;
    // both have Id = 2
}

class A
{
    public long Id {get;set;}
}
void Main()
{
var a=新列表{new a{Id=1},new a{Id=2};
a、 FirstOrDefault(x=>x.Id==1.Id=2;
//两者都有Id=2
}
甲级
{
公共长Id{get;set;}
}

它只需要在我的头脑中起作用,上面的例子也是如此,但事实并非如此。我错在哪里?

首先,您的计数是按在组中找到的条目数进行计数,因此您不需要指定它来计数id的条目数,这将是相同的

其次,要检索第一个Id,从分组数据中获取第一个条目,然后从中获取Id属性

你基本上知道答案了

var groups = 
      models
        .GroupBy(x => new { x.IdA })
        .Select
        (
            x => 
                new Model
                { 
                    Id = (x.Count() > 1) ? 0 : x.First().Id, 
                    IdA = x.Key.IdA,
                    IdW = (x.Count() > 1) ? 0 : x.First().IdW,
                    Qty = x.Sum(y => y.Qty) 
                }
        );

应该与您执行的
Id
几乎相同。这可以缩短为
x.Count()>1?0:x.First().Id
。使用左外联接。看msdn:我真的没有想到这一点!谢谢