将来自不同来源的组合数据收集到一个IEnumerable对象中

问题描述 投票:0回答:2

我在下面有此方法,该方法从不同来源收集数据并将其作为一个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对象。

是否有一种方法可以用一种方法执行此操作,或者我需要创建某种其他方法来执行此操作?

谢谢!

c# linq asp.net-core-2.0 ienumerable
2个回答
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
投票

为什么不创建“ 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();

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.