简单linq相当于嵌套for循环

  var zz = from aa in quoteCaseModel.SingleProductList
                                     from bb in aa.CaseProductList
                                     where bb.Catagory == 14
                                     select bb;

  var dkkkk = from aaaa in quoteCaseModel.ServiceProductList
                                        where strProductID.Contains(aaaa.Id.ToString())
                                        select aaaa;

### 使用 LINQ 模拟 `for` 循环实现多行多列拼接 在 C# 中,LINQ 本身是一种声明式查询语法,不直接支持传统的 `for` 循环控制结构。然而,可以通过使用索引、分组和投影操作来模拟循环逻辑,并将多个对象合并为一行。 假设有一个 `List<IRow>` 类型的集合,其中每个 `IRow` 对象包含多个字段(如 `Cell1`, `Cell2`, ...),目标是将每 **N 行** 的数据合并为一行,将这些行中的特定字段进行拼接形成新的列。 #### 示例代码: ```csharp using System; using System.Collections.Generic; using System.Linq; public interface IRow { string Cell1 { get; } string Cell2 { get; } } public class Row : IRow { public string Cell1 { get; set; } public string Cell2 { get; set; } } public class Program { public static void Main() { var data = new List<IRow> { new Row { Cell1 = "A1", Cell2 = "B1" }, new Row { Cell1 = "A2", Cell2 = "B2" }, new Row { Cell1 = "A3", Cell2 = "B3" }, new Row { Cell1 = "A4", Cell2 = "B4" }, new Row { Cell1 = "A5", Cell2 = "B5" }, new Row { Cell1 = "A6", Cell2 = "B6" } }; int groupSize = 3; var result = data .Select((row, index) => new { Index = index, Row = row }) .GroupBy(x => x.Index / groupSize) .Select(g => { var rows = g.Select(x => x.Row).ToList(); return new { Column1 = string.Join(" ", rows.Select(r => r.Cell1)), Column2 = string.Join(" ", rows.Select(r => r.Cell2)) }; }); foreach (var item in result) { Console.WriteLine($"{item.Column1}, {item.Column2}"); } } } ``` 此代码通过 `.Select((row, index) => new { Index = index, Row = row })` 获取每个元素的索引,并利用 `GroupBy(x => x.Index / groupSize)` 将数据划分为固定大小的组[^1]。之后对每组数据进行投影,使用 `string.Join()` 方法将多个字段拼接为字符串,从而模拟了类似 `for` 循环的功能。 #### 输出结果: ``` A1 A2 A3, B1 B2 B3 A4 A5 A6, B4 B5 B6 ``` --- ### 扩展功能:动态处理不确定列数的情况 若不知道具体有多少列需要拼接,可以使用反射或字典形式读取所有属性并进行拼接。例如: ```csharp var resultDynamic = data .Select((row, index) => new { Index = index, Row = row }) .GroupBy(x => x.Index / groupSize) .Select(g => { var rows = g.Select(x => x.Row).ToList(); var properties = typeof(IRow).GetProperties() .Where(p => p.PropertyType == typeof(string)); var mergedRow = properties.ToDictionary( prop => prop.Name, prop => string.Join(" ", rows.Select(r => (string)prop.GetValue(r))) ); return mergedRow; }); ``` 该方式通过反射获取所有字符串类型的属性,并将其值拼接为一行输出,适用于任意数量的列[^2]。 --- ### 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值