[英]Parsing a string made from a LINQ statement to a method
我想通過只e.Trip
我的string.Format
中引用的方法tripChoose
。 截至目前,它試圖傳遞一個未為該方法格式化的字符串。 如果我可以通過字符串的Trip部分,它會工作。 有什么建議么?
private void LoadExpenseListSums()
{
expenseTotalSelect.Items.Clear();
var sortedList=
from e in roster
group e by e.Trip into expenseCollect
select new { Trip = expenseCollect.Key, SumAmount = expenseCollect.Sum(e => e.Amount) };
foreach (var e in sortedList)
tripChoose.Items.Add(string.Format("{0} | ${1}", e.Trip, e.SumAmount));
}
看起來您的expenseTotalSelect是一個ASP.NET Select控件,您正在做的事情最終會在結果HTML中添加一個元素,該元素僅由文本標識,例如:
<select id='expenseTotalSelect'>
<option>Hawaii | $5000</option>
<option>London | $4000</option>
...
</select>
在您的expenseTotalSelect.Items.Add調用中,您可能最好不要執行以下操作:
expenseTotalSelect.Items.Add(
new ListItem(string.Format("{0} | ${1}", e.Trip, e.SumAmount),e.Trip));
現在,當您渲染為HTML時,您將獲得以下內容:
<select id='expenseTotalSelect'>
<option value='Hawaii'>Hawaii | $5000</option>
<option value='London'>London | $4000</option>
...
</select>
並且更容易引用tripChoose.SelectedItem.Value
,它僅包含此示例的e.Trip值(夏威夷或倫敦)
是的,現在我們實際上知道我們正在處理什么,我懷疑你想要這樣的東西:
private void LoadExpenseListSums()
{
expenseTotalSelect.Items.Clear();
var dateSorted =
from e in roster
group e by e.Trip into tripGroup
select new { Trip = tripGroup.Key,
Text = string.Format("{0} | ${1}",
tripGroup.Key,
tripGroup.Sum(e => e.Amount) };
tripChoose.DataSource = dateSorted;
tripChoose.DisplayMember = "Text";
tripChoose.ValueMember = "Trip";
}
這做了一些假設:ase, - roster
是一個內存中的集合:如果不是,你可能需要在格式化之前調用AsEnumerable
,以便在本地發生 - 匿名類型使用數據綁定; 我不確定是否是這種情況,但我希望是這樣的
然后,您稍后使用SelectedValue
成員來查找行程ID。
認為您應該使用注釋中建議的對象,但假設expenseTotalSelect
是List<string>
並且tripChoose
綁定到它,您可以這樣做:
(string)tripChoose.SelectedItem.Split('|')[0].Replace(" ", string.Empty)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.