linq group.by - closure的意外行为?

时间:2016-12-01 13:44:39

标签: linq closures

我有List<Model> modelList ,其中Model包含属于`GUID?的属性 GuidProperty 。保证此列表中的所有元素都不具有空值,因为列表是使用扩展名

过滤的
modelList.Where(x=>x.GuidProperty.HasValue)

此外,每个GUID都是唯一的。

现在尝试通过

遍历此列表modelList
foreach (var model in modelList.GroupBy(x => x.GuidProperty.Value)){
        doSomething();
    }

我认识到没有modelList.Count这样的群组对我来说没有意义。在我的情况下,一组是&#34;缺少&#34;。

这是由我创建此列表modelList的方式引起的吗?:

//all guid are unique in the example
 List<Model> modelList = new List<Model>();

            using (var entities = _modelContext.EntitiesNoChanges)
            {
                modelList.AddRange(
                    entities.OrderProcessingItems.Where(x => x.GuidProperty.HasValue).ToList());


            }

//manually filled list of unique guids contained in modelList
List<Guid> guidList = new List<Guid>();

            foreach (var model in modelList)
            {
                // ReSharper disable once PossibleInvalidOperationException
                var guid = model.GuidProperty.Value;
                if (guidList.Contains(guid))
                {
                    continue;
                }
                guidList.Add(guid);
            }

// grouped list that should have n groups | n=modelList.Count
foreach (var model in modelList.GroupBy(x => x.GuidProperty.Value)){
        doSomething();
    }

更新

以下是实际问题:

-       guidList    Count = 4   System.Collections.Generic.List<System.Guid>
+       [0] {46952518-1529-4b0f-8123-6bad36057e84}  System.Guid
+       [1] {80395ccb-2307-4bea-b772-69b36ea8d663}  System.Guid
+       [2] {e1161daf-8c7b-4b31-a987-694e4563e0e6}  System.Guid
+       [3] {2c44861e-073b-42b2-8fbf-6ff0e1cc0b7b}  System.Guid
+       Raw View        

//this is the grouping for modelList - ignore namings...
-       offeringRateGroup   {System.Linq.Lookup<System.Guid, slModel.Db.OrderProcessingItem>.Grouping}  System.Linq.IGrouping<System.Guid, slModel.Db.OrderProcessingItem> {System.Linq.Lookup<System.Guid, slModel.Db.OrderProcessingItem>.Grouping}
+       Key {46952518-1529-4b0f-8123-6bad36057e84}  System.Guid
        System.Collections.Generic.ICollection<slModel.Db.OrderProcessingItem>.Count    3   int
        System.Collections.Generic.ICollection<slModel.Db.OrderProcessingItem>.IsReadOnly   true    bool
        count   3   int
+       elements    {slModel.Db.OrderProcessingItem[4]} slModel.Db.OrderProcessingItem[]

guidList是手动创建的,涵盖了列表中的所有模型属性。

更新 代码顺序

0 个答案:

没有答案