代码之家  ›  专栏  ›  技术社区  ›  Megrez7

C#ToArray转换合并为一行,导致数组元素更改

  •  0
  • Megrez7  · 技术社区  · 3 月前

    我想知道是否可以合并 ToArray 将得到的数组单个元素转换为一个语句。

    这工作得很好

    var response = Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
    
    response[0].Summary = "Some text";
    
    return response;
    

    但是,此函数只返回包含在中的字符串 Summary

    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray()[0].Summary = "Some text";
    
    2 回复  |  直到 3 月前
        1
  •  1
  •   Dmitrii Bychenko    3 月前

    好吧,要有Linq唯一的解决方案,你可以尝试添加三元运算符:

      Summary = index == 1 
        ? "Some text" 
        : Summaries[Random.Shared.Next(Summaries.Length)]
    

    代码:

    return Enumerable
      .Range(1, 5)
      .Select(index => new WeatherForecast {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = index == 1 
          ? "Some text" // 1st item is special one
          : Summaries[Random.Shared.Next(Summaries.Length)] // business as usual
      })
      .ToArray();
    

    另一种(更普遍的)可能性是 Select 最后:

    return Enumerable
      .Range(1, 5)
       ...
       /* A lot of Linq here */
       ...
      .Select((value, index) => index == 0 
         ? "Some text"
         : value)
      .ToArray();
    
        2
  •  1
  •   Ivan Petrov    3 月前

    如果你必须在一行上,你总是可以使用这样的扩展方法:

    public static class Extensions {
        public static T[] WithChangeAt<T>(this T[] arr, int index, Action<T> change)
        where T : class {
            if ((uint)index >= (uint)arr.Length)
                throw new ArgumentException("Index is out of bounds for the array");
                
            change(arr[index]);
            return arr;
        }
    }
    

    然后

    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray()
    .WithChangeAt(0, x => x.Summary = "Some text");