我有一个班级ExpenseItem
和一个基于该班级的列表。
我目前正在设计一个带有组合框的表单,该组合框允许我选择特定类型的ExpenseItem
Trip,并在列表框中显示所有结果。
表单代码(tripSelect
是组合框,listExpenses
是列表框):
private void LoadExpenseList()
{
tripSelect.Items.Clear();
var dateSorted =
from e in roster
group e by e.Trip into tripGroup
select new { Trip = tripGroup.Key };
foreach (var e in dateSorted)
tripSelect.Items.Add(e.Trip);
}
private void LoadExpenseDetail()
{
listExpenses.Items.Clear();
var dateSorted =
from e in roster
orderby e.Trip
select e;
foreach (var e in dateSorted) ;
}
private void ExpenseRecorderForm_Load(object sender, EventArgs e)
{
}
private void tripSelect_SelectedIndexChanged(object sender, EventArgs e)
{
selectedExpense = (ExpenseItem)roster.ToFind((string)tripSelect.SelectedItem);
listExpenses.Items.Add(selectedExpense);
}
private void listExpenses_SelectedIndexChanged(object sender, EventArgs e)
{
tripTextBox.Text = selectedExpense.Trip;
tripTextBox.Enabled = false;
descriptionTextBox.Text = selectedExpense.Description;
amountTextBox.Text = selectedExpense.Amount.ToString();
paymentMethodTextBox.Text = selectedExpense.PaymentMethod;
dateExpenseTimePicker.Value = selectedExpense.Date;
dateExpenseTimePicker.Enabled = true;
noteTextBox.Text = selectedExpense.Note;
}
答案 0 :(得分:1)
我无法编写像myVariable.Where();因为它不是IEnumerable
我真的不明白你的意思。
对于错误,它表示您无法从IEnumerable
投射到ExpenseItem
。你必须像最后一个例子那样应用它并返回项而不是IEnumerable
。我会跳过Where
子句直接使用FirstOrDefault
public ExpenseItem ToFind(string trip)
{
return this.FirstOrDefault(e => e.Trip == trip);
}
我认为this
是一个自定义的集合,否则Linq扩展将无法在this
上运行
修改
如果你真的想要这个......
public IEnumerable<ExpenseItem> ToFind(string trip)
{
return this.Where(e => e.Trip == trip);
}
然后你需要处理来自呼叫者的列表。
private void tripSelect_SelectedIndexChanged(object sender, EventArgs e)
{
IEnumerable<ExpenseItem> selectedExpenses = roster.ToFind((string)tripSelect.SelectedItem);
foreach(ExpenseItem item in selectedExpenses)
listExpenses.Items.Add(item);
}
答案 1 :(得分:0)
如果你将使用它:
public IEnumerable<ExpenseItem> ToFind(string trip)
{
return this.Where(e => e.Trip == trip);
}
您需要使用此功能,请注意FirstOrDefault:
selectedExpense = roster
.ToFind((string)tripSelect.SelectedItem)
.FirstOrDefault();
您的selectedExpense不是IEnumerable:
private ExpenseItem selectedExpense;
通过良好的设计,如果取景器只匹配一个记录,例如按主键
public ExpenseItem ToFind(string expenseId)
{
return this.FirstOrDefault(e => e.ExpenseId == expenseId);
}
,使用FirstOrDefault,然后,你可以简单地使用这样的finder方法:
selectedExpense = roster.ToFind(idHere);