如何根据同一对象列表的其他特性值指定特性值
本文关键字:其他 列表 何根 对象 | 更新日期: 2023-09-27 18:17:00
我的结构
public struct lumCummulativeData
{
public byte[] lumId { get; set; }
public float ledPwr { get; set; }
public float batChargePwr { get; set; }
public float batDischargePwr { get; set; }
public float ledPwrAvg { get; set; }
public float batChargePwrAvg { get; set; }
public float batDischargePwrAvg { get; set; }
public float ledPwrWh { get; set; }
public float batChargeWh { get; set; }
public float batDischargeWh { get; set; }
public int count { get; set; }
public string lumName { get; set; }
}
申报列表
public static List<lumCummulativeData> cummulativeDataList
= new List<lumCummulativeData>();
我将为lumId赋值cummulativeData.lumId = lumIdByte;
(分配了一些id值(
现在我想写一些条件,以便列表对象(同一对象(的其他属性值必须基于与我从网络数据包中获得的lumId匹配的lumId来分配
我尝试的逻辑
for(int i=0; i<cummulativeDataList.Count(); i++)
{
bool lumIdMatched = cummulativeDataList[i]
.lumIdCummulativeData
.SequenceEqual(packet.SelfID);
if(lumIdMatched == true)
{
cummulativeData.ledPwr += packet.LedPwr;
cummulativeData.batChargePwr += packet.batchrgpwr;
cummulativeData.batDischargePwr += packet.battdispwr;
cummulativeData.count++;
cummulativeDataList.Add(cummulativeData);
}
}
列表对象正在增加,而不是向现有对象添加字段值。这是我在分配LumId时创建的。我想要一些逻辑,它迭代到所有现有对象的LumId,并在LumId与我从网络获得的数据包LumId匹配时添加其他字段值
您应该使用cummulactiveDataList[i]而不是cummulactiveData。
此外,检查您是否真的需要添加功能。因为你想更改它,而不是添加新的。
for (int i=0; i<cummulativeDataList.Count(); i++)
{
bool lumIdMatched = cummulativeDataList[i]
.lumIdCummulativeData
.SequenceEqual(packet.SelfID);
if (lumIdMatched == true)
{
cummulativeDataList[i].ledPwr += packet.LedPwr;
cummulativeDataList[i].batChargePwr += packet.batchrgpwr;
cummulativeDataList[i].batDischargePwr += packet.battdispwr;
cummulativeDataList[i].count++;
//cummulativeDataList.Add(cummulativeData);
}
}
我可以看到两个问题。首先在您的线上
bool lumIdMatched = cummulativeDataList[i].lumIdCummulativeData.SequenceEqual(packet.SelfID);
lumIdCumulativeData不是lumCumulative Data结构的属性,因此它可能应该是:
bool lumIdMatched = cummulativeDataList[i].lumId.SequenceEqual(packet.SelfID);
其次,只要匹配,就会向cumulativeDataList添加一个新的列表元素。相反,您应该修改当前正在迭代的列表元素。
for(int i=0;i<cummulativeDataList.Count();i++)
{
bool lumIdMatched = cummulativeDataList[i].lumId.SequenceEqual(packet.SelfID);
if(lumIdMatched==true)
{
cummulativeDataList[i].ledPwr+= packet.LedPwr;
cummulativeDataList[i].batChargePwr += packet.batchrgpwr;
cummulativeDataList[i].batDischargePwr += packet.battdispwr;
cummulativeDataList[i].count++;
}
}
您可以使用LINQ以不同的方式来处理这个问题,它更优雅:
cummulativeDataList
.Where(lumCD => lumCD.lumId.SequenceEqual(packet.SelfID))
.ForEach(lumCD => {
lumCD.ledPwr += packet.LedPwr;
lumCD.batChargePwr += packet.batchrgpwr;
lumCD.batDischargePwr += packet.battdispwr;
lumCD.count++;
}
);