下面我有这种方法,该方法从不同来源收集数据并将其作为一个IEnumerable返回。
我遇到了麻烦,想出如何将所有源组合成一个TotalRoomContents类型的对象。
TotalRoomContents的类型为IEnumerable<String>
。
这是未完成的方法:
public static TotalRoomContents GetRoomContents(this Dungeon dungeon)
{
var customArmor = dungeon.Rooms
.Select(pe => pe.Room)
.Where(e => e.Monster.IsActive);
// check each customArmor object to see if it exists in the MapLookupByRoomId dictionary
if (customArmor != null && MapLookupByRoomId.ContainsKey(customArmor.Id))
// add all item(s) of type customArmor to TotalRoomContents()
if(dungeon.RoomType?.InventoryContent != null)
{
// add item(s) from dungeon.RoomType?.InventoryContent to TotalRoomContents()
}
return new TotalRoomContents()
}
如您所见,我不知道如何将项目添加到TotalRoomContents
对象中。
这些项目将来自dungeon.RoomType?.InventoryContent
以及linq查询中找到的所有customArmor
对象。
有没有一种方法可以做到这一点,或者我需要创建某种其他方法来做到这一点?
谢谢!
答案 0 :(得分:1)
您可以创建一个包装类来解决这个问题。可能的实现看起来像这样
public class AggregateEnumerable<T> : IEnumerable<T> {
private readonly IEnumerable<T>[] _sources;
public AggregateEnumerable( params IEnumerable<T>[] sources ) {
_sources = sources;
}
public IEnumerator<T> GetEnumerator() {
foreach( var source in _sources ) {
var enumerator = source.GetEnumerator();
while( enumerator.MoveNext() )
yield return enumerator.Current;
}
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
然后您将像
一样使用它var firstEnumerable = new[] { "Peter", "John" };
var secondEnumerable = new[] { "Thomas", "George" };
var myEnum = new AggregateEnumerable<string>(firstEnumerable, secondEnumerable);
foreach( var value in myEnum )
Console.WriteLine(value);
答案 1 :(得分:1)
为什么不创建“ RoomContent”列表(表示房间可以容纳的任何内容),然后开始添加其他查询的所有不同结果?
List<RoomContent> TotalRoomContents = new List<RoomContent>();
if (/* Whatever condition needs to be met */)
{
TotalRoomContents.Add(/* Whatever you may want */);
}
另外,您应该知道直到代码需要枚举Linq查询才会执行,因此,基本上,您可以逐步构建查询:
// This is just to simulate the data source
IQueryable<RoomContent> query = allPossibleRoomContents.AsQueryable();
query = query.Where(x => x.ContentDescription = "Sword");
query = query.Where(x => x.ContentDescription = "Axe");
// This is where the actual work is done
return query.ToList();
希望这会有所帮助!