我有observablecollection,我在按钮点击事件中填充文本框。在我的项目是一个类,我有列表>> public List _RoomNumber = new List();我想只将observablecollection值发送到_RoomNumber列表。例如,如果observablecollection包含这4个值:15,20,2323,3232我希望_RoomNumber上下文相同所以这个:15,20,2323,3232
我希望我的问题很明确。 这是我的观察收集:
ObservableCollection<CheckInData> _CheckInCollection = new ObservableCollection<CheckInData>();
public ObservableCollection<CheckInData> CheckInCollection
{
get { return _CheckInCollection; }
}
public class CheckInData
{
public string RoomNumber { get; set; }
public decimal Price { get; set; }
public string Currecny { get; set; }
public decimal Discount { get; set; }
public string CheckOut { get; set; }
public int TotalDay { get; set; }
public decimal TotalPrice { get; set; }
public int CheckOutYear { get; set; }
public int CheckOutMonth { get; set; }
public int CheckOutDay { get; set; }
public Boolean IncToday { get; set; }
}
这是我试图放入列表的方式。问题是observablecollection包含102和305._RoomNumber只获得值“1”。请帮忙
private void btnPrintInvoice_Click(object sender, RoutedEventArgs e)
{
//This is Class where my List _RoomNumber is
DataToExcel.Invoice inv = new DataToExcel.Invoice();
foreach (CheckInData coll in CheckInCollection)
{
for (int i = 0; i < _CheckInCollection.Count; i++)
{
inv._RoomNumber.Add(coll.RoomNumber[i].ToString());
}
}
}
答案 0 :(得分:1)
您可以使用
var roomnumbers = CheckInCollection.Select(x => x.RoomNumber);
inv._RoomNumber = new List(roomnumbers);
或者,如果您想重用现有的List
实例,
inv._RoomNumber.Clear();
inv._RoomNumber.AddRange(roomnumbers);
但这似乎不是你的情况。
请注意,在您的代码中,内部循环和外部循环遍历同一个集合: - )
答案 1 :(得分:1)
您需要做一些小修改。试试这个:
private void btnPrintInvoice_Click(object sender, RoutedEventArgs e)
{
//This is Class where my List _RoomNumber is
DataToExcel.Invoice inv = new DataToExcel.Invoice();
foreach (CheckInData coll in CheckInCollection)
{
inv._RoomNumber.Add(coll.RoomNumber.ToString());
}
}
您无需使用索引访问RoomNumber。它不是一个集合。
答案 2 :(得分:0)
using System.Linq;
...
ObservableCollection<string> ListA = new ObservableCollection<string>();
List<string> ListB = ListA.ToList<string>();