我想选择OrderId&从多个词典中排,并创建一个包含行列表的订单列表。
我正在努力解决这个问题的代码是:
var listOfDictionaries = new List<Dictionary<string, string>>();
var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);
var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);
var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);
var grouped = listOfDictionaries.SelectMany(d =>
d.Where(kvp =>
kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
.GroupBy(a => a.Key).ToList();
public class Order
{
public Order()
{
OrderRows = new List<OrderRow>();
}
public string OrderId { get; set; }
public List<OrderRow> OrderRows { get; set; }
}
public class OrderRow
{
public string OrderRowId { get; set; }
}
任何人都知道如何解决这个问题?
答案 0 :(得分:2)
您可以先选择订单,然后选择这样的内容行。
var orderFieldName = "OrderId";
var orders = listOfDictionaries.Select(dict => dict[orderFieldName]).Distinct();
var grouped = orders.Select(order => new Order
{
OrderId = order,
OrderRows = listOfDictionaries.Where(dict => dict[orderFieldName] == order)
.Select(item => new OrderRow {OrderRowId = item["Row"]}).ToList()
});
答案 1 :(得分:2)
你需要做
var result = listOfDictionaries.Select(x => new { OrderId = x["OrderId"], Row = x["Row"] })
.GroupBy(x => x.OrderId)
.Select(x => new { OrderId = x.Key, Values = x.Select(y => y.Row) });
答案 2 :(得分:1)
我觉得你的词典代码不会运行,因为它不允许你在同一个列表中输入重复的键值。所以我在这里使用Struct
列表创建了一个解决方案class Stackoverflow
{
struct OrderData
{
public string OrderID { get; set; }
public string Row { get; set; }
}
static void Main(string[] args)
{
string strInputOrderID = "ORD1";
////Using Struct List
List<OrderData> objOrderDataList = new List<OrderData>();
OrderData objOrderData = new OrderData();
objOrderData.OrderID = "ORD1";
objOrderData.Row = "1";
objOrderDataList.Add(objOrderData);
objOrderData = new OrderData();
objOrderData.OrderID = "ORD2";
objOrderData.Row = "2";
objOrderDataList.Add(objOrderData);
objOrderData = new OrderData();
objOrderData.OrderID = "ORD3";
objOrderData.Row = "3";
objOrderDataList.Add(objOrderData);
objOrderData = new OrderData();
objOrderData.OrderID = "ORD1";
objOrderData.Row = "4";
objOrderDataList.Add(objOrderData);
List<OrderData> resultOrderDataList = (from data in objOrderDataList
where data.OrderID.Equals(strInputOrderID)
select data).ToList();
Console.ReadLine();
}
}
我已经运行它并且工作正常。 请检查并在评论中告诉我。
答案 3 :(得分:0)
就像@Nikhil Agrawal所说:
检查this
var result = listOfDictionaries
.Select(x => new { OrderId = x["OrderId"], Row = x["Row"] })
.GroupBy(x => x.OrderId)
.Select(x => new Order{
OrderId = x.Key,
OrderRows = x.Select(y => new OrderRow{OrderRowId = y.Row}).ToList()
});