C# 将列表转换为ObservableCollection
我需要将我从api调用中得到的列表转换成一个ObservableCollection,以放入我的图中 我尝试了以下两种方法: 方法1:C# 将列表转换为ObservableCollection,c#,xamarin,C#,Xamarin,我需要将我从api调用中得到的列表转换成一个ObservableCollection,以放入我的图中 我尝试了以下两种方法: 方法1: ObservableCollection<ChartDataModel> test = new ObservableCollection<ChartDataModel>(_CoinHistoryGraph as List<CoinHistoryModel>); 方法2上的错误: 'System.Collections.Gen
ObservableCollection<ChartDataModel> test = new ObservableCollection<ChartDataModel>(_CoinHistoryGraph as List<CoinHistoryModel>);
方法2上的错误:
'System.Collections.Generic.IEnumerable<CoinMarketCap.SHARED.ViewModels.ChartDataModel>' to 'System.Collections.ObjectModel.ObservableCollection<CoinMarketCap.SHARED.ViewModels.ChartDataModel>'.
要从CoinHistoryModel列表创建ObservableCollection,最好使用以下代码:
CoinHistory = new ObservableCollection<ChartDataModel>(_CoinHistoryGraph.Select(x => new ChartDataModel(float.Parse(x.price_btc), double.Parse(x.timestamp))));
CoinHistory=newobserveCollection(_CoinHistoryGraph.Select(x=>newChartDataModel(float.Parse(x.price_btc),double.Parse(x.timestamp)));
您的第一段代码不起作用,因为您希望从CoinHistoryModel类型的集合中创建ChartDataModel类型的ObservableCollection关于你的第二段代码,错误信息已经很清楚了。您希望将IEnumerable对象显式强制转换为ObservableCollection one。
要从type1集合创建type1的ObservableCollection,可以将该集合作为ObservableCollection第一个构造函数参数传递。新ObservableCollection中的泛型参数需要与传递到构造函数的
IEnumerable
或列表的泛型参数匹配。因此,您需要传入一个列表
,而不是列表
或列表
尝试将选择
结果传递给可观察集合
构造函数。
'System.Collections.Generic.IEnumerable<CoinMarketCap.SHARED.ViewModels.ChartDataModel>' to 'System.Collections.ObjectModel.ObservableCollection<CoinMarketCap.SHARED.ViewModels.ChartDataModel>'.
public class GraphModel
{
public GraphModel(float pricebtc, double time_stamp)
{
price_btc = pricebtc;
timestamp = time_stamp;
}
public float price_btc { get; set; }
public double timestamp { get; set; }
}
public class CoinHistoryModel
{
public string name { get; set; }
public string price_btc { get; set; }
public string timestamp { get; set; }
}
CoinHistory = new ObservableCollection<ChartDataModel>(_CoinHistoryGraph.Select(x => new ChartDataModel(float.Parse(x.price_btc), double.Parse(x.timestamp))));