使用GroupConsecutive
您将在答案末尾找到的扩展方法,您可以执行以下操作:
List<Day> days = new List<Day>
{
new Day { Name = "Sunday", Hours= "8am - 9pm" },
new Day { Name = "Monday", Hours= "8am - 10pm" },
new Day { Name = "Tuesday", Hours= "8am - 10pm" },
new Day { Name = "Wednesday", Hours= "8am - 10pm" },
new Day { Name = "Thursday", Hours= "9am - 10pm" },
new Day { Name = "Friday", Hours= "8am - 11pm" },
new Day { Name = "Saturday", Hours= "8am - 11pm" },
};
var query = from g in days.GroupConsequtive(d => d.Hours)
select new {
Name = g.Count() == 1 ? g.First().Name :
String.Format("{0}-{1}", g.First().Name.Substring(0, 3), g.Last().Name.Substring(0, 3)),
Hours = g.Key
};
枚举结果:
foreach (var item in query)
Console.WriteLine("{0} {1}", item.Name, item.Hours);
输出:
Sunday 8am - 9pm
Mon-Wed 8am - 10pm
Thursday 9am - 10pm
Fri-Sat 8am - 11pm
连续分组的扩展方法:
public static class LazyExtensions
{
public static IEnumerable<IGrouping<TKey, TElement>> GroupConsecutive<TKey, TElement>(
this IEnumerable<TElement> source, Func<TElement, TKey> keySelector)
{
if (!source.Any())
yield break;
var comparer = Comparer<TKey>.Default;
Grouping<TKey, TElement> group = null;
foreach (var item in source)
{
var key = keySelector(item);
if (group == null)
group = new Grouping<TKey, TElement>(key);
if (comparer.Compare(group.Key, key) != 0)
{
yield return group;
group = new Grouping<TKey, TElement>(key);
}
group.Elements.Add(item);
}
yield return group;
}
private class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
{
public Grouping(TKey key)
{
Key = key;
Elements = new List<TElement>();
}
public List<TElement> Elements { get; private set; }
public TKey Key { get; private set; }
public IEnumerator<TElement> GetEnumerator()
{
return Elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
这个怎么运作?它创建分组(自定义类,实现 IGrouping 接口)并将具有相同键值的连续元素添加到该组。如果新的键值到达,则返回分组。因此,所有序列都按连续的键值分组。