使用linq选择冒号值
本文关键字:选择 linq 使用 | 更新日期: 2023-09-27 18:08:06
我想选择一个冒号具有where条件的值(它从idlist的值变成)。然后这些值将被添加到列表中。我试过的代码如下。
怎么做?
public ActionResult Create(string UrunId, List<String> idlist)
{
List<String> fiyatList = new List<string>();
if (idlist != null)
{
ViewBag.abc = idlist;
int i;
for(i=0;i<idlist.Count();i++)
{
var sorgu = from a in db.Urunlers where a.UrunId == Int32.Parse(idlist[i]) select new { a.UrunFiyat};
fiyatList.Add(sorgu.ToString());
}
ViewBag.fiyat = fiyatList;
}
return View();
}
但是返回的是查询而不是值
<<p> UrunList视图/strong>@foreach (BillApplication.Models.Urunler con in Model)
{
<tr>
<td>
<input id="urunsec" type="checkbox" name="cbList" value="@con.UrunId.ToString()" onchange="ClickMe(this)" />
</td>
<td>@con.UrunId</td>
<td>@con.UrunAdi</td>
<td><div id="=fiyatdiv"> @con.UrunFiyat </div></td>
<td>@con.AltkategoriId</td>
<td colspan="4"></td>
</tr>
}
<tr>
<td>
<input id="submit" type="submit" value="Gönder" name="Command" />
</td>
</tr>
<<p> 创建视图/strong> <td>
<textarea id="txt_urunler" rows="2" cols="20" style="border-style:inset; width:150px; border-width:0.2em; border-color:gainsboro">
@if (@ViewBag.abc != null)
{
foreach (var i in ViewBag.abc)
{
@i
}
}
</textarea>
</td>
<td>
<textarea id="txt_fiyat" rows="2" cols="20" style="border-style:inset; width:150px; border-width:0.2em; border-color:gainsboro">
@if (@ViewBag.fiyat != null)
{
foreach (var i in ViewBag.fiyat)
{
@i
}
}
</textarea>
</td>
创建动作
public ActionResult Create(string UrunId, List<String> idlist, List<String> fiyatList)
{
if (idlist != null)
{
ViewBag.abc = idlist;
}
if (fiyatList != null)
{
ViewBag.fiyat = fiyatList;
}
return View();
}
[HttpPost]
public ActionResult Create(Faturalar mReg, string Command, string txt_cari)
{
if (Command == "hesapla") { }
else if (Command == "Ürün Seç") { return RedirectToAction("UrunList"); }
return View();
}
您不应该创建额外的对象,在本例中(sorgu)
你正在创建一个sorgu,它不会被用来做任何进一步的计算。
for(i = 0; i < idlist.Count(); i++)
{
fiyatList.Add(db.Urunlers.Where(a => a.UrunId == int.Parse(idlist[i])
.FirstOrDefault()).ToString());
}
为干净的代码创建一个lambda。这是你的选择。
你也应该使用Model而不是ViewBag。
试试这个
foreach(var item in idlist)
{
int reqInt;
if(!int.TryParse(item.Trim(), out reqInt)
{
throw new Exception("Invalid Value");
}
var sorgu = (from a in db.Urunlers
where a.UrunId == reqInt
select a.UrunFiyat).FirstOrDefault();
fiyatList.Add(sorgu.ToString());
}
或
var finalList = db.Urunlers.Where(x => idlist.Select(int.Parse).ToList().Contains(x.UrunId)).Select(v => v.UrunFiyat).ToList();