[英]how to use string variable as column name in asp.net mvc
我不確定這種事情是否可能。 但是我想使用變量作為列名。
以下是我必須使用的代碼
cartall.CartItems = cartdatas.Select(a => new Models.DTO.CartDTO.CartVM()
{
VariationId = a.VariationId,
ColorName = a.ColorName,
StockInfo = rpstock.FirstOrDefault(x => x.Id == a.VariationId).Yellow
}).ToList();
但是我想像下面那樣使用它。
我要使用的代碼:
cartall.CartItems = cartdatas.Select(a => new Models.DTO.CartDTO.CartVM()
{
VariationId = a.VariationId,
ColorName = a.ColorName,
StockInfo = rpstock.FirstOrDefault(x => x.Id == a.VariationId).(a.ColorName)
}).ToList();
我的Stock.cs
public class Stock:Base.BaseEntity
{
public int Id { get; set; }
public int? Yellow { get; set; }
public int? Red { get; set; }
public int? White { get; set; }
public virtual VariationEntity.Variation Variation { get; set; }
}
我的變體
public class Variation : Base.BaseEntity
{
public int Id { get; set; }
public int OwnerProductID { get; set; }
public string SKU { get; set; }
public short? Height { get; set; }
public short? Width { get; set; }
public decimal? Price { get; set; }
public string Delivery { get; set; }
public int? OrderLimit { get; set; }
public virtual StockEntity.Stock Stock { get; set; }
}
我在stock.cs和variant.cs之間有1對1的關系
這應該工作:
StockInfo = rpstock.FirstOrDefault(x => x.Id == a.VariationId && x.ColorName == a.ColorName)
我創建了一個Method
,它將使用一個list
和一個Column Name
然后返回該列的value
。 請檢查一下。
碼:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public class Stock
{
public int Id { get; set; }
public int? Yellow { get; set; }
public int? Red { get; set; }
public int? White { get; set; }
}
public static void Main()
{
List<Stock> list = new List<Stock>();
list.Add(new Stock(){Id=1, Yellow = 50, Red = 0, White = 205});
list.Add(new Stock(){Id=2, Yellow = 20, Red = 200, White = 35});
list.Add(new Stock(){Id=3, Yellow = 0, Red = 100, White = 155});
string ColumnName = "Yellow";
var Test1 = GetColumnValue(list.Where(m=>m.Id == 1).ToList(), ColumnName);
var Test2 = GetColumnValue(list.Where(m=>m.Id == 2).ToList(), ColumnName);
var Test3 = GetColumnValue(list.Where(m=>m.Id == 3).ToList(), ColumnName);
Console.WriteLine(Test1);
Console.WriteLine(Test2);
Console.WriteLine(Test3);
}
public static object GetColumnValue(List<Stock> items, string columnName)
{
var values = items.Select(x => x.GetType().GetProperty(columnName).GetValue(x)).FirstOrDefault();
return values;
}
}
您必須像下面這樣在代碼中使用GetColumnValue
方法:
cartall.CartItems = cartdatas.Select(a => new Models.DTO.CartDTO.CartVM()
{
VariationId = a.VariationId,
ColorName = a.ColorName,
StockInfo = GetColumnValue(rpstock.FirstOrDefault(x => x.Id == a.VariationId).ToList(), a.ColorName)
}).ToList();
您可以在DotNetFiddle中運行此解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.