代码之家  ›  专栏  ›  技术社区  ›  SledgeHammer

有单线LINQ方法可以做到这一点吗?

  •  -1
  • SledgeHammer  · 技术社区  · 8 年前

    假设输入文本文件的格式为:

    blaha|blahb
    blahc|blahd
    

    File.ReadAllLines(...).Select(x =>
    {
       string[] arr = x.Split(new char[] { '|' });
       return new Item(arr[0], arr[1]);
    };
    

    如果我把第一行改为 .Select(x => x.Split(new char[] { '|' }) 它将返回每一行和每一列作为数组元素,这不是我想要的。有没有linq“内联”方式来拆分列并更新对象?

    4 回复  |  直到 8 年前
        1
  •  6
  •   Aaron Roberts    8 年前

    您可以将多个选择链接在一起。

    File.ReadAllLines(...)
        .Select(line => line.Split(new [] { '|' }))
        .Select(arr => new Item(arr[0], arr[1]))
    

    public class Item {
        ...
        public static Item FromPipeDelimitedText(string text) {
            var arr = text.Split(new [] { '|' };
            return new Item(arr[0], arr[1]);
        }
    }
    

    File.ReadAllLines(...).Select(Item.FromPipeDelimitedText);
    

    使用这种方法,可以独立测试从文件中提取数据的功能

        2
  •  1
  •   15ee8f99-57ff-4f92-890c-b56153    8 年前

    “Cooler”是基于观点的,但你不能说这不是LINQ,也不能说它有多个分号。

    var items =
        from line in File.ReadAllLines(myfile)
        let arr = line.Split(new char[] { '|' })
        select new Item(arr[0], arr[1]);
    

    Here's a filddle demonstrating the above code . System.IO.File.ReadAllLines(string path) 退货 string[] --文件中的行数组。

        3
  •  1
  •   JuanR    8 年前

    File.ReadAllLines(someFileName)
        .Select(x => x.Split('|'))
        .Select(a => new Item(a[0], a[1]));
    

    然而,这假设线路 分为[至少]两部分,根据个人经验,这是不容易处理错误的。

    我建议避免使用单行方法,除非您绝对确定没有问题行,或者使用函数委托来管理实例化和错误处理。

        4
  •  0
  •   code4life    8 年前

    使用 SelectMany

    // returns IEnumerable<Item>
    File.ReadAllLines(...).SelectMany(x =>
    {
       string[] arr = x.Split(new char[] { '|' });
       return new Item(arr[0], arr[1]);
    }