复杂的Linq分组

unk*_*own 14 .net c# linq

我是Stack Overflow的新手,但试图提供尽可能多的信息

我有以下课程结构

public class ItemEntity
{
    public int ItemId { get; set; }
    public int GroupId { get; set; }
    public string GroupName { get; set; }
    public DateTime ItemDate { get; set; }
    public string Field1 { get; set; }
    public string Filed2 { get; set; }
    public string Field3 { get; set; }
    public string Field4 { get; set; }
    public int Duration { get; set; }        
}

public class MasterEntity
{
    public ItemEntity Item { get; set; }
    public List<int> ItemList { get; set; }
    public List<int> GroupList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将列表组合ItemEntityMasterEntity.分组文件是Field1,Field2和Field3.

到目前为止,我已完成了分组,如下所示

var items = new List<ItemEntity>
            {
                new ItemEntity
                {
                    ItemId = 100,
                    GroupId = 1,
                    GroupName= "Group 1",
                    ItemDate = new DateTime(2018,10,17),
                    Duration = 7,
                    Field1 = "Item Name 1",
                    Filed2 = "aaa",
                    Field3= "bbb",
                    Field4= "abc"
                },
                new ItemEntity
                {
                    ItemId = 150,
                    GroupId = 2,
                    GroupName= "Group 2",
                    ItemDate = new DateTime(2018,10,17),
                    Duration = 5,
                    Field1 = "Item Name 1",
                    Filed2 = "aaa",
                    Field3= "bbb",
                    Field4= "efg"
                },
                new ItemEntity
                {
                    ItemId = 250,
                    GroupId = 3,
                    GroupName= "Group 3",
                    ItemDate = new DateTime(2018,10,15),
                    Duration = 7,
                    Field1 = "Item Name 1",
                    Filed2 = "aaa",
                    Field3= "bbb",
                    Field4= "xyz"
                }
            };


            var group = items.GroupBy(g => new
            {
                g.Field1,
                g.Filed2,
                g.Field3
            }).Select(s => new MasterEntity
            {
                Item = new ItemEntity
                {
                    Field1 = s.Key.Field1,
                    Filed2 = s.Key.Filed2,
                    Field3 = s.Key.Field3
                },
                ItemList = s.Select(g => g.ItemId).ToList(),
                GroupList = s.Select(g => g.GroupId).ToList()
            }).ToList();
Run Code Online (Sandbox Code Playgroud)

在这个组中,我想通过实际的ItemDate和Duration进一步分割它,所以它看起来如下所示

预期产出

基本上,我想在这种情况下将这个组分成三组.

由于只有Group3的日期为15日至17日,因此它将是一个组.从第17组到第22组,第1组,第2组和第3组是相同的.这将成为另一个团体.最后只有Group1有22到24,所以它成为另一组

最终的分组数据就像

G1
{
 ItemEntity :{
 ItemDate : 15/10/2018,
 Duration : 2,
 Field1 : "Item Name 1",
 Filed2 : "aaa",
 Field3 : "bbb",
    },
ItemList: {250},
GroupList:{3}
}

,
G2
{
 ItemEntity :{
 ItemDate : 17/10/2018,
 Duration : 5,
 Field1 : "Item Name 1",
 Filed2 : "aaa",
 Field3 : "bbb",
},
ItemList: {100,150,250},
GroupList:{1,2,3}
}
,
G3
{
 ItemEntity :{
 ItemDate : 22/10/2018,
 Duration : 2,
 Field1 : "Item Name 1",
 Filed2 : "aaa",
 Field3 : "bbb",
},
ItemList: {100},
GroupList:{1}
}
Run Code Online (Sandbox Code Playgroud)

Net*_*age 2

这非常具有挑战性。我使用了一些方便的扩展方法,我已经让它变得更容易,并创建了一个HashSet默认使用的子类SetEqual(.Net确实需要一些内置的成员相等集合类)。

HashSetEq首先,当其成员匹配时实现相等的类:

public class HashSetEq<T> : HashSet<T>, IEquatable<HashSetEq<T>> {
    private static readonly IEqualityComparer<HashSet<T>> SetEq = HashSet<T>.CreateSetComparer();

    public override int GetHashCode() => SetEq.GetHashCode(this);
    public override bool Equals(object obj) => obj != null && (obj is HashSetEq<T> hs) && this.Equals(hs);
    public bool Equals(HashSetEq<T> other) => SetEq.Equals(this, other);

    public HashSetEq(IEnumerable<T> src) : base(src) {
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,一些对IEnumerable. 一个扩展将 an 转换IEnumerable为 a HashSetEq,以便于创建密钥集合。另一个扩展是GroupBy在谓词为真时分组的变体,基于ScanPair实现 APL 扫描运算符的成对版本的扩展。

public static class IEnumerableExt {
    public static HashSetEq<T> ToHashSetEq<T>(this IEnumerable<T> src) => new HashSetEq<T>(src);


    // TKey combineFn((TKey Key, T Value) PrevKeyItem, T curItem):
    // PrevKeyItem.Key = Previous Key
    // PrevKeyItem.Value = Previous Item
    // curItem = Current Item
    // returns new Key
    public static IEnumerable<(TKey Key, T Value)> ScanPair<T, TKey>(this IEnumerable<T> src, TKey seedKey, Func<(TKey Key, T Value), T, TKey> combineFn) {
        using (var srce = src.GetEnumerator()) {
            if (srce.MoveNext()) {
                var prevkv = (seedKey, srce.Current);

                while (srce.MoveNext()) {
                    yield return prevkv;
                    prevkv = (combineFn(prevkv, srce.Current), srce.Current);
                }
                yield return prevkv;
            }
        }
    }

    public static IEnumerable<IGrouping<int, T>> GroupByWhile<T>(this IEnumerable<T> src, Func<T, T, bool> testFn) =>
        src.ScanPair(1, (kvp, cur) => testFn(kvp.Value, cur) ? kvp.Key : kvp.Key + 1)
           .GroupBy(kvp => kvp.Key, kvp => kvp.Value);
}
Run Code Online (Sandbox Code Playgroud)

为了对日期范围进行分组,我GroupBySequential基于GroupByWhile内联进行了扩展,这样我就可以按顺序日期运行和匹配的GroupIds 集进行分组。GroupBySequential取决于整数序列,因此我需要一个基本日期来计算日期序列号,因此我使用所有项目中最早的日期:

var baseDate = items.Min(i => i.ItemDate);
Run Code Online (Sandbox Code Playgroud)

现在我可以计算出答案了。

对于每组项目,我根据 展开每个项目涵盖的所有日期,Duration并将每个日期与原始项目相关联:

var group = items.GroupBy(g => new {
    g.Field1,
    g.Filed2,
    g.Field3
})
.Select(g => g.SelectMany(i => Enumerable.Range(0, i.Duration).Select(d => new { ItemDate = i.ItemDate.AddDays(d), i }))
Run Code Online (Sandbox Code Playgroud)

现在我有了所有单独的日期+项目,我可以为每个日期将它们分组。

              .GroupBy(di => di.ItemDate)
Run Code Online (Sandbox Code Playgroud)

然后按日期对每个日期+项目进行分组,并按该日期对组进行分组并按日期排序。

              .GroupBy(dig => new { ItemDate = dig.Key, Groups = dig.Select(di => di.i.GroupId).ToHashSetEq() })
              .OrderBy(ig => ig.Key.ItemDate)
Run Code Online (Sandbox Code Playgroud)

baseDate通过按日期排序,我可以将具有相同 的连续日期分组在一起(使用 中的天数) Groups

              .GroupByWhile((prevg, curg) => (int)(prevg.Key.ItemDate - baseDate).TotalDays + 1 == (int)(curg.Key.ItemDate - baseDate).TotalDays && prevg.Key.Groups.Equals(curg.Key.Groups))
Run Code Online (Sandbox Code Playgroud)

最后,我可以将每个连续日期组中的信息提取到 a 中MasterEntity,并将其作为整个答案 a List

              .Select(igg => new MasterEntity {
                  Item = new ItemEntity {
                      ItemDate = igg.First().Key.ItemDate,
                      Duration = igg.Count(),
                      Field1 = g.Key.Field1,
                      Filed2 = g.Key.Filed2,
                      Field3 = g.Key.Field3
                  },
                  ItemList = igg.First().First().Select(di => di.i.ItemId).ToList(),
                  GroupList = igg.First().Key.Groups.ToList()
              })
)
.ToList();
Run Code Online (Sandbox Code Playgroud)