我不确定这样的事情是否可行。但我想使用变量作为列名。
以下是我必须使用的代码
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; }
}
My Variation.cs
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和variation.cs之间有一对一的关系
答案 0 :(得分:0)
这应该有效:
StockInfo = rpstock.FirstOrDefault(x => x.Id == a.VariationId && x.ColorName == a.ColorName)
答案 1 :(得分:0)
我创建了一个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中运行此解决方案。