Blazor中如何通过TelerikGrid对比数据并高亮差异单元格
问题
我有两个动态列表:
ObservableCollection<dataClass> currentList { get; set; } = new ObservableCollection<dataClass>();
和
ObservableCollection<dataClass> previousList { get; set; } = new ObservableCollection<dataClass>();
数据类定义如下:
public class dataClass { public string FullName { get; set; } public int SportsId { get; set; } public string SportsName { get; set; } public DateTime DateOfBirth { get; set; } }
我用TelerikGrid展示currentList的数据,希望当单元格数据与previousList中对应同一用户的数据存在差异(比如SportsId、SportsName变更)时,高亮该单元格。尝试通过Razor.cs文件中的CompareData函数实现,但无法正确获取previousList中的数据进行对比,原函数代码如下:
public string CompareData(string? SportsName) { string? currentSportsName = SportsName; string? prevSportsName = **idkwhattoputhereorhowtodoit**; if (currentSportsName != prevSportsName) { return "red"; } else { return ""; } }
解决方案
无需保留两个动态列表,仅保留currentList即可,dataClass和TelerikGrid的定义保持不变。修改后的CompareData函数通过反射实现数据对比:
public string CompareData(string? SportsName) { if (currentList.Count > 1) { var currentItem = currentList[0]; PropertyInfo? prop = currentItem.GetType().GetProperty(SportsName); string currentValue = (string)prop.GetValue(currentItem); var previousItem = currentList[1]; PropertyInfo? prevProp = previousItem.GetType().GetProperty(SportsName); string previousValue = (string)prevProp.GetValue(previousItem); if (currentValue != previousValue) { return "red"; } else { return ""; } } else { return ""; } }
该方案利用反射技术,通过属性名动态获取currentList中前后项的对应字段值进行对比,实现差异单元格的高亮需求。
内容的提问来源于stack exchange,提问作者remdon
相关产品推荐
相关产品推荐

