您现在的位置是:网站首页> 编程资料编程资料
Queryable.Union 方法实现json格式的字符串合并的具体实例_实用技巧_
2023-05-25
317人已围观
简介 Queryable.Union 方法实现json格式的字符串合并的具体实例_实用技巧_
1.在数据库中以json字符串格式保存,如:[{"name":"张三","time":"8.592","area":"27.27033","conc":"4.12136"},{"name":"李四","time":"9.100","area":"56.21229","conc":"4.57692"}]
2.添加新内容后合并不相同的数据。如果name相同,以最新的数据替换原来的数据。
如:数据库中原保存的数据是[{"name":"张三","time":"8.592","area":"27.27033","conc":"4.12136"},{"name":"李四","time":"9.100","area":"56.21229","conc":"4.57692"}]
新加的数据为[{"name":"张三","time":"12","area":"27.70533","conc":"4.12136"},{"name":"王五","time":"4","area":"77","conc":"8.788"}]
则替换后的数据为[{"name":"张三","time":"12","area":"27.70533","conc":"4.12136"},{"name":"王五","time":"4","area":"77","conc":"8.788"},{"name":"李四","time":"9.100","area":"56.21229","conc":"4.57692"}]
代码如下:
public void InsertOrUpdateOnlyItem(List
{
var listLeInsert = new List
var listLeUpdate = new List
foreach (var le in listLe)
{
tblLims_Ana_LE_Import_Common model = le;
var own = CurrentRepository.Find(a => a.fldTaskID == model.fldTaskID
&& a.fldBizCatID == model.fldBizCatID
&& a.fldItemCode == model.fldItemCode
&& a.fldNumber == model.fldNumber
&& a.fldSampleCode == model.fldSampleCode);
if (own != null)
{
var ser = new JavaScriptSerializer();
var listown = ser.Deserialize>>(own.fldImportData); //原数据
var listmodel = ser.Deserialize>>(model.fldImportData); //新数据
IEqualityComparer
own.fldImportData = ser.Serialize(listmodel.Union(listown, ec)); //合并数据
listLeUpdate.Add(own);
}
else
{
listLeInsert.Add(model);
}
}
CurrentRepository.UpdateAll(listLeUpdate);
CurrentRepository.InsertAll(listLeInsert);
CurrentRepository.Save();
}
tblLims_Ana_LE_Import_Common 为数据库中存数据的表
Union() 方法中用到的自定义比较类:
///
/// 自定义比较类
///
public class EntityComparer : IEqualityComparer
{
public bool Equals(Dictionary
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
return false;
return x["name"] == y["name"]; //如果名称相同就不追加
}
public int GetHashCode(Dictionary
{
if (ReferenceEquals(obj, null)) return 0;
int hashName = obj["name"] == null ? 0 : obj["name"].GetHashCode();
int hashCode = obj["name"] == null ? 0 : obj["name"].GetHashCode();
return hashName ^ hashCode;
}
}
相关内容
- Json返回时间的格式中出现乱码问题的两种解决方案_实用技巧_
- .NET 单点登录解决方案_实用技巧_
- Asp.net 自带报表的使用详解_实用技巧_
- ASP.NET服务器端控件RadioButtonList,DropDownList,CheckBoxList的取值、赋值用法_实用技巧_
- ASP.NET中使用Ajax的方法_实用技巧_
- 三种方法让Response.Redirect在新窗口打开_实用技巧_
- asp.net动态产生checkbox(数据源为DB或内存集合)_实用技巧_
- ADO.NET无连接模式的详细介绍_实用技巧_
- AspNetPager分页控件定义及应用样式示例介绍_实用技巧_
- C#保存上传来的图片示例代码_实用技巧_
