我有这样的班
public class RoomDetails
{
public int RoomIndexID {get;set;} --(This is No of Rooms)
public int roomcategoryID {get;set;} -- (This is No of Category that room have)
public decimal roomPrice{get;set;}
public string roomCategory{get;set;}
}
所以我有这样的RoomDetails列表(数据)
所以我想按照下面的步骤阅读这个列表。
请问你是否有任何问题重新评定我的问题。
这是一个例子
我的数据列表是这样的
(实际上A,B,C是RoomIndexID 's,A1,B1,B2,B3,C1,C2是roomcategoryID 's)所以我想这样读。
发布于 2016-11-05 16:43:09
如果您想要"LINQy“解决方案,它会有点复杂。请注意,它是LINQ,因此如果您有.ToList()
(例如从EntityFramework),则需要首先调用IQueryable
。
var total = list.GroupBy(x=>x.RoomIndexID)
.Select(x=>x.Count())
.Aggregate(1, (s,d)=>s*d);
var counts = list.GroupBy(x => x.RoomIndexID)
.ToDictionary(x => x.Key, x => x.Count());
var nums = list.GroupBy(x => x.RoomIndexID)
.Select(x => x.Select((p, i) => new {i, p}))
.SelectMany(x => x)
.ToList();
var result = Enumerable.Range(0, total)
.Select(x =>
nums.Where(y => {
var c = counts[y.p.RoomIndexID];
var p = counts
.Where(z => z.Key > y.p.RoomIndexID)
.Aggregate(1, (s,d)=>s*d.Value);
return y.i == x/p%c;
})
.Select(y => y.p)
);
发布于 2017-01-22 16:44:37
简单得多,像这样的东西可以做到:
var groups = list // your input
.GroupBy(x => x.RoomIndexID)
.Select(x => x.ToList())
.ToList();
var result = groups.Skip(1).Aggregate(
groups.Take(1),
(x, y) => x.SelectMany(z => y, (a, b) => a.Concat(new[] { b }).ToList()));
基本上,我们的想法是首先进行GroupBy
房间索引,这样就可以得到相同类型的内部序列,然后在这些序列之间执行交叉连接(对这些序列来说,SelectMany
是可以的),最后,对连接结果进行Aggregate
。这三个步骤应该做得很好。使用以下命令式样式示例可以更清楚地说明所涉及的步骤:
var groups = list
.GroupBy(x => x.RoomIndexID)
.Select(x => x.ToList());
IEnumerable<IEnumerable<RoomDetails>> result = null;
foreach (var item in groups)
{
if (result == null)
result = new[] { item };
else
result = result.SelectMany(x => item, (x, y) => x.Concat(new[] { y }));
}
如果我们对Aggregate
有一个适当的过载,就可以在一步内完成这件事,它以序列中的第一项的Func
作为种子。
// Say you have:
public static TAccumulate Aggregate<TSource, TAccumulate>(
this IEnumerable<TSource> source,
Func<TSource, TAccumulate> seeder,
Func<TAccumulate, TSource, TAccumulate> func)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (func == null)
throw new ArgumentNullException(nameof(func));
using (IEnumerator<TSource> iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
throw new InvalidOperationException("Empty sequence.");
TAccumulate result = seeder(iterator.Current);
while (iterator.MoveNext())
{
result = func(result, iterator.Current);
}
return result;
}
}
// Then you could do:
var result = list
.GroupBy(x => x.RoomIndexID)
.Select(x => x.ToList())
.Aggregate(
x => Enumerable.Repeat(x, 1),
(x, y) => x.SelectMany(z => y, (a, b) => a.Concat(new[] { b }).ToList()));
这整件事看起来很复杂,因为在框架或语言中都有一些遗漏的部分。理想情况下(我假设在许多函数式语言中),您应该能够:
var result = list
.GroupBy(x => x.RoomIndexID)
.Aggregate(x => x.Yield(), (x, y) => x.SelectMany(z => y, (a, b) => a.Append(b)));
https://stackoverflow.com/questions/40440192
复制相似问题