只能在IEnumerable上枚举一次

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

给出以下代码(xUnit测试):

[Fact]
public void SetFilePathTest()
{
    // Arrange
    IBlobRepository blobRepository = null;
    IEnumerable<Photo> photos = new List<Photo>() 
    {
        new Photo()
        {
            File = "1.jpg"
        },
        new Photo()
        {
            File = "1.jpg"
        }
    };

    IEnumerable<CloudBlockBlob> blobs = new List<CloudBlockBlob>()
    {
        new CloudBlockBlob(new Uri("https://blabla.net/media/photos/1.jpg")),
        new CloudBlockBlob(new Uri("https://blabla.net/media/photos/2.jpg"))
    };

    // Act
    photos = blobRepository.SetFilePath2(photos, blobs);

    // Assert
    Assert.Equal(2, photos.Count());
    Assert.Equal(2, photos.Count());
}

这是SetFilePath2方法:

public static IEnumerable<T> SetFilePath2<T>(this IBlobRepository blobRepository, IEnumerable<T> entities, IEnumerable<CloudBlockBlob> blobs) where T : BlobEntityBase
{
    var firstBlob = blobs.FirstOrDefault();

    if (firstBlob is null == false)
    {
        var prefixLength = firstBlob.Parent.Prefix.Length;
        return entities
            .Join(blobs, x => x.File, y => y.Name.Substring(prefixLength), (entity, blob) => (entity, blob))
            .Select(x =>
            {
                x.entity.File = x.blob.Uri.AbsoluteUri;
                return x.entity;
            });
    }
    else
    {
        return Enumerable.Empty<T>();
    }
}

正如你所看到的,我断言同样的事情是2次。但只有第一个断言成功。当我使用调试器时,我只能枚举一次集合。所以在第二个Assert它没有产生任何物品。

谁能解释我为什么会这样?我真的没有看到这个代码的任何问题,而不是解释这种行为。

c#
1个回答
0
投票

每当你调用.Count()时,你基本上都会调用blobRepository.SetFilePath2(photos, blobs).Count()并在使用Select时修改实体。如果你不打算改变原始值,我建议在new语句中使用Select。这就是为什么你得到不同的结果。

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