List to IReadOnlyList

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

我有一个接受这些参数的函数:

public decimal[] Calculate(IReadOnlyList<(decimal High, decimal Low, decimal Close)> candles, int period)

但我不记得该怎么称呼

List<BinanceKline> list = ...
Calculate(list.Select(e => new { e.High, e.Low, e.Close }), 20);

它返回明显的错误。

错误CS1503:参数1:无法从'System.Collections.Generic.IEnumerable <>'转换为'System.Collections.Generic.IReadOnlyList '

c# list
2个回答
4
投票

[List<T>实现IReadOnlyList<T>,因此您可以这样做:

var list = list
    .Select(e => (e.High, e.Low, e.Close))
    .ToList();

Calculate(list, 20);

注意,您还需要选择一个元组而不是匿名对象。


2
投票

嗯,对于

public decimal[] Calculate(
  IReadOnlyList<(decimal High, decimal Low, decimal Close)> candles, 
  int period) {...}

我们应该提供[IReadOnly]Listint(请注意.ToList()):

Calculate(
  list.Select(e => (e.High, e.Low, e.Close)).ToList(), 
  20);

list.Select不足时:只是IEnumerable<T>

编辑:您可能需要*将Calculate方法重新设计为

public decimal[] Calculate<T> (
  IEnumerable<T> data, 
  int period,
  Func<T, decimal> high,
  Func<T, decimal> low,
  Func<T, decimal> close) {

  //TODO: validation here 

  List<(decimal High, decimal Low, decimal Close)> candles = data
    .Select(item => (high(item), low(item), close(item)));

  //TODO: logic from former Calculate here
}

然后称它为>

Calculate(
  list, 
  20, 
  item => item.High, 
  item => item.Low,  
  item => item.Close);
© www.soinside.com 2019 - 2024. All rights reserved.