我在下面有此方法,该方法从不同来源收集数据并将其作为一个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
对象。
是否有一种方法可以用一种方法执行此操作,或者我需要创建某种其他方法来执行此操作?
谢谢!
您应该添加一些缺少的说明,例如(您应该添加一个arraylist,来自TotalRoomContent的数据收集将在那里临时存储,并通过返回作为arraylist对象来完成方法。
您可以创建一个包装类来解决这个问题。可能的实现看起来像这样
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);