使用 Lambda 表达式获取相同属性名的不同属性值 JSON 数据
以下是使用 Lambda 表达式将 ProductPropertyValue 集合中相同属性名的不同属性值整理为 JSON 格式的实现:
1. 使用 Lambda 表达式进行分组和转换
csharp
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
public class ProductPropertyService
{
public string GetGroupedPropertiesJson(List<ProductPropertyValue> properties)
{
// 使用 Lambda 表达式按属性名分组并转换为 JSON
var groupedProperties = properties
.GroupBy(p => p.PropertyName) // 按属性名分组
.Select(g => new
{
PropertyName = g.Key,
Values = g.Select(p => new
{
p.PropertyValue,
p.ImageUrl,
p.ImageType,
p.ProductPropertyValueId
}).ToList()
})
.ToList();
// 序列化为 JSON
return JsonConvert.SerializeObject(groupedProperties, Formatting.Indented);
}
// 更简洁的版本,直接返回字典格式
public string GetGroupedPropertiesAsDictionary(List<ProductPropertyValue> properties)
{
var result = properties
.GroupBy(p => p.PropertyName)
.ToDictionary(
g => g.Key,
g => g.Select(p => new
{
p.PropertyValue,
p.ImageUrl,
p.ImageType,
p.ProductPropertyValueId
}).ToList()
);
return JsonConvert.SerializeObject(result, Formatting.Indented);
}
// 如果只需要属性值和图片URL
public string GetSimpleGroupedProperties(List<ProductPropertyValue> properties)
{
var result = properties
.GroupBy(p => p.PropertyName)
.ToDictionary(
g => g.Key,
g => g.Select(p => new
{
Value = p.PropertyValue,
Image = p.ImageUrl
}).ToList()
);
return JsonConvert.SerializeObject(result, Formatting.Indented);
}
}2. 使用示例
csharp
// 假设这是从数据库获取的属性值列表
List<ProductPropertyValue> propertyValues = dbContext.ProductPropertyValues
.Where(p => p.ProductId == productId)
.ToList();
// 创建服务实例
var service = new ProductPropertyService();
// 使用 Lambda 表达式获取分组后的 JSON
string jsonResult = service.GetGroupedPropertiesJson(propertyValues);
// 输出或使用 JSON
Console.WriteLine(jsonResult);3. 直接在 LINQ 查询中使用 Lambda 表达式
csharp
// 直接从数据库查询并转换为 JSON
public string GetProductPropertiesJson(Guid productId)
{
using (var context = new ApplicationDbContext())
{
var groupedProperties = context.ProductPropertyValues
.Where(p => p.ProductId == productId)
.GroupBy(p => p.PropertyName)
.Select(g => new
{
PropertyName = g.Key,
Values = g.Select(p => new
{
p.PropertyValue,
p.ImageUrl,
p.ImageType,
p.ProductPropertyValueId
}).ToList()
})
.ToList();
return JsonConvert.SerializeObject(groupedProperties, Formatting.Indented);
}
}4. 使用更复杂的 Lambda 表达式处理数据
csharp
// 包含过滤和排序的 Lambda 表达式
public string GetFilteredGroupedProperties(List<ProductPropertyValue> properties)
{
var groupedProperties = properties
.Where(p => !string.IsNullOrEmpty(p.PropertyValue)) // 过滤空值
.OrderBy(p => p.ProductPropertyValueSort) // 按排序字段排序
.GroupBy(p => p.PropertyName)
.Select(g => new
{
PropertyName = g.Key,
Values = g.Select(p => new
{
p.PropertyValue,
p.ImageUrl,
p.ImageType,
p.ProductPropertyValueId
}).ToList()
})
.OrderBy(g => g.PropertyName) // 按属性名排序
.ToList();
return JsonConvert.SerializeObject(groupedProperties, Formatting.Indented);
}5. 使用 Lambda 表达式创建扁平化结构
csharp
// 创建扁平化的属性列表(不分组)
public string GetFlattenedProperties(List<ProductPropertyValue> properties)
{
var flattened = properties
.Select(p => new
{
p.PropertyName,
p.PropertyValue,
p.ImageUrl,
p.ImageType,
p.ProductPropertyValueId
})
.ToList();
return JsonConvert.SerializeObject(flattened, Formatting.Indented);
}6. 预期的 JSON 输出
使用上述 Lambda 表达式生成的 JSON 输出将类似于:
json
[
{
"PropertyName": "颜色",
"Values": [
{
"PropertyValue": "红色",
"ImageUrl": "/images/red.jpg",
"ImageType": "jpg",
"ProductPropertyValueId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
},
{
"PropertyValue": "蓝色",
"ImageUrl": "/images/blue.jpg",
"ImageType": "jpg",
"ProductPropertyValueId": "b2c3d4e5-f6g7-8901-bcde-f23456789012"
}
]
},
{
"PropertyName": "尺寸",
"Values": [
{
"PropertyValue": "大号",
"ImageUrl": null,
"ImageType": null,
"ProductPropertyValueId": "c3d4e5f6-g7h8-9012-cdef-345678901234"
},
{
"PropertyValue": "中号",
"ImageUrl": null,
"ImageType": null,
"ProductPropertyValueId": "d4e5f6g7-h8i9-0123-defg-456789012345"
}
]
}
]7. 在 ASP.NET MVC 控制器中使用
csharp
public class ProductController : Controller
{
private readonly ApplicationDbContext _context;
public ProductController(ApplicationDbContext context)
{
_context = context;
}
public ActionResult GetProductProperties(Guid productId)
{
// 使用 Lambda 表达式查询和分组数据
var groupedProperties = _context.ProductPropertyValues
.Where(p => p.ProductId == productId)
.GroupBy(p => p.PropertyName)
.Select(g => new
{
PropertyName = g.Key,
Values = g.Select(p => new
{
p.PropertyValue,
p.ImageUrl,
p.ImageType,
p.ProductPropertyValueId
}).ToList()
})
.ToList();
return Json(groupedProperties, JsonRequestBehavior.AllowGet);
}
}8. 注意事项
性能优化:对于大数据集,考虑使用
AsNoTracking()提高查询性能:csharp
_context.ProductPropertyValues.AsNoTracking().Where(...)空值处理:可以使用
DefaultIfEmpty()处理可能为空的分组自定义序列化设置:可以通过
JsonSerializerSettings自定义 JSON 序列化行为:csharp
var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DateFormatString = "yyyy-MM-dd HH:mm:ss" }; return JsonConvert.SerializeObject(groupedProperties, settings);
这些 Lambda 表达式示例展示了如何高效地对 ProductPropertyValue 集合进行分组和转换,生成结构化的 JSON 数据,便于在前端使用。
[System.Web.Http.HttpGet] // [System.Web.Http.Route("api/product/ProductDetails/{id}")] public IHttpActionResult ProductProperty(string id)//商品详细介绍 { Guid gid = new Guid(id); var ppm = HrbgwDB.Products.Find(gid); var pname = ppm.ProductName; var pprice = ppm.SellingPrice; var productsimg = HrbgwDB.ProductImages.Where(p => (p.ProductId == gid)) .OrderByDescending(a => a.ProductImageSort) .Take(5) .ToList(); var iCategories = ppm.CategoryId; var result = new { ProductId = gid, ProductName = pname, SmallImgName = ppm.SmallImageUrl, ProductPrice = pprice, CategoryId = iCategories, ProductDescription = ppm.Description, ProductsImages = productsimg, }; return Json(result);和 // 另一种格式:简单键值对格式 public string GroupPropertiesAsDictionary(List<ProductPropertyValue> properties) { var result = properties .GroupBy(p => p.PropertyName) .ToDictionary( g => g.Key, g => g.Select(p => new { Value = p.PropertyValue, ImageUrl = p.ImageUrl, ImageType = p.ImageType }).ToList() ); return JsonConvert.SerializeObject(result, Formatting.Indented); } 结合 }