我有一个包含值的字符串列表。我需要根据字符串的特定索引为列表赋值。下面是我的相同代码。
var fruits = new string[] { "Color", "Price", "Shape ", "Nutrients" };
var fruitDetails = db.Fruits.Where(f => f.FruitId == 5).Select(f => new FruitModel{Id = f.FruitId,Category=f.Category, Color = f.FruitColor, Price=f.FruitPrice, Shape = f.FruitShape, Nutrients = f.FruitNutrients}).FirstOrDefault();
现在我需要使用从Linq查询中获得的结果基于水果列表填充列表。
foreach (var item in fruits )
{
var fruitData = new fruitData ();
fruitData.Category= fruitDetails .Category;
fruitData.Description= ; //This has to be the value of Color if item is color,value of price if item is price and so on...
fruitList.Add(fruitData);
}
因此,基于循环值是什么,需要填充相应的值。我不想使用Reflection。有替代方法吗?
答案 0 :(得分:3)
如果您使用{/ 1}}语句
,该怎么办?switch
答案 1 :(得分:1)
我建议在FruitModel
添加一个属性,该属性根据实例的类别返回描述,并且可以使用静态Dictionary
将类别映射到访问者函数:
public class FruitModel {
public int Id;
public string Category;
public string Color;
public double Price;
public string Shape;
public string Nutrients;
static Dictionary<string, Func<FruitModel, string>> catmap = new Dictionary<string, Func<FruitModel, string>> {
{ "Color", fm => fm.Color },
{ "Price", fm => fm.Price.ToString() },
{ "Shape", fm => fm.Shape },
{ "Nutrients", fm => fm.Nutrients },
};
public string Description {
get => catmap[Category](this);
}
public static List<string> FruitDetailCategories {
get => catmap.Keys.ToList();
}
}
您还可以创建静态属性以返回详细信息类别,而不是将列表放在其他位置。
(显然你可以在属性体中使用开关而不是Dictionary
,但它不适合提供细节类别。)
现在您可以轻松构建列表:
var fruitList = new List<FruitData>();
foreach (var fruit in fruitDetails) {
var fd = new FruitData();
fd.Category = fruit.Category;
fd.Description = fruit.Description;
fruitList.Add(fd);
}