我正在生成对象列表现在我需要通过使用字典来更改具有特定id内部的对象列表,其中包含特定id对象数据。
这是我的完整代码。
m_Query = m_Query + " LEFT JOIN LIBRARY lib5 ON lib5.LIBRARY_ID = comm.STATUS2";
if (comObj.ProductsID != "" || comObj.ProductsID != null)
{
m_Query = m_Query + " where prod1.PRODUCT_ID in ";
string allproducts = string.Empty;
allproducts = comObj.ProductsID;
m_Query = m_Query + " ("+ allproducts + ") order by prod1.PRODUCT_ID desc";
}
DataSet dsPck = new DataSet();
dsPck = conn.GetDataSet(m_Query, CommandType.Text, ConnectionState.Open);
DataTable dt = new DataTable();
dt = dsPck.Tables[0];
if (dt.Rows.Count > 0)
{
for (int i = 0; i<dt.Rows.Count; i++)
{
CommitmentReport Info = new CommitmentReport();
Info.PRODUCT_ID = Convert.ToInt64(dt.Rows[i]["PRODUCT_ID"].ToString());
Info.ProductName = dt.Rows[i]["ProductName"].ToString();
Info.COMMITMENT_ID = Convert.ToInt64(dt.Rows[i]["COMMITMENT_ID"].ToString());
Info.ReferenceNo = dt.Rows[i]["ReferenceNo"].ToString();
Info.CreatedDate = Convert.ToDateTime(dt.Rows[i]["CreatedDate"].ToString());
Info.Numbers = dt.Rows[i]["Numbers"].ToString();
Info.Catalogue = dt.Rows[i]["Catalogue"].ToString();
Info.Specification = Convert.ToInt64(dt.Rows[i]["Specification"].ToString());
Info.Type = dt.Rows[i]["Type"].ToString();
Info.SubmissionType = dt.Rows[i]["SubmissionType"].ToString();
Info.ApprovalStatus = dt.Rows[i]["ApprovalStatus"].ToString();
Info.Country = dt.Rows[i]["Country"].ToString();
Info.Status = dt.Rows[i]["Status"].ToString();
// Info.Count = x;
commLst.Add(Info);
}
}
我正在返回对象列表,但现在我需要更改包含相关对象的每个特定键(PID)内部。
答案 0 :(得分:1)
从我理解的问题CommObj
是List<ComRep>
,您希望将项目提供给与特定密钥匹配的字典。如果是这样,你可以尝试以下
string ProductID = "PID1";
var selectedProduct = CommObj.Where(x=> x.ProductID == ProductID)
.ToDictionary(y=> y.ProductID, y=> y);
var allProducts = CommObj.ToDictionary(y=> y.ProductID, y=> y); // all items to dictionary
或者你可以试试这个,如果你需要一个字典而不是这个列表。
Dictionary<string,ComRep> ComRepDict = new Dictionary<string,ComRep>();
for (int i = 0; i < dt.Rows.Count; i++)
{
if(!ComRepDict.ContainsKey(dt.Rows[i]["PID"].ToString())
{
ComRepDict.Add( dt.Rows[i]["PID"].ToString(), new ComRep(){
PID = dt.Rows[i]["PID"].ToString();
PName = dt.Rows[i]["PName"].ToString();
PDesc = dt.Rows[i]["PDesc"].ToString();
commitmentid = dt.Rows[i]["commitmentid"].ToString();
country = dt.Rows[i]["country"].ToString();
status = dt.Rows[i]["status"].ToString();
Count = x;
});
}
更新:
var groupedProducts = CommObj.GroupBy(x=> x.ProductID)
.ToDictionary(y=> y.Key, y=> y.ToList());
返回groupedProducts
,将返回类型更改为Dictionary<string,List<ComRep>>
答案 1 :(得分:1)
如果你想要一个字典而不是列表,那就是这样:
var dictionary = new Dictionary<string, List<ComRep>>();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
ComRep Info = new ComRep();
....
/// Your object initialization here
if(!dictionary.ContainsKey(Info.PID))
dictionary.Add(Info.PID, new List<ComRep>{ Info });
else
dictionary[Info.PID].Add(Info);
}
}
return dictionary;