简体   繁体   English

有单行LINQ方式可以做到这一点吗?

[英]Is there single-line LINQ way to do this?

Imagine an input text file with the format: 想象一下一个输入文本文件,其格式为:

blaha|blahb
blahc|blahd

ie a pipe separated file with 2 columns. 即,管道分隔的文件有2列。 Right now, I'm loading it like this: 现在,我正在像这样加载它:

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

If I change the first line to .Select(x => x.Split(new char[] { '|' }) it's going to return every row and column as an array element which is not what I want. Is there a linq "inline" way to split the columns and new up the object? 如果我将第一行更改为.Select(x => x.Split(new char[] { '|' })它将以数组元素的形式返回每一行和每一列,这不是我想要的。 “内联”方式拆分列和新建对象?

You can chain multiple selects together. 您可以将多个选择链接在一起。

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

One thing i do for this type of work as well is to create helper methods that you can use as Method Groups if this type of functionality is going to be reused. 对于这种类型的工作,我要做的一件事就是创建辅助方法,如果要重用这种类型的功能,则可以将其用作方法组。

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

then 然后

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

with this method the functionality that extracts the data from the file can be tested independently 使用此方法,可以独立测试从文件中提取数据的功能

"Cooler" is about as opinion-based as it gets, but you can't argue that this isn't LINQ, or that it has more than one semicolon. “ 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) returns string[] -- an array of lines from the file. System.IO.File.ReadAllLines(string path)返回string[] -文件中的行数组。

You can always do this: 您可以随时这样做:

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

This however assumes that the line always splits in [at least] two, which from personal experience is not easily error-handled. 但是,这假定行总是至少分成两部分,从个人经验来看,这不容易进行错误处理。

I would suggest avoiding a single-line approach unless you are absolutely sure there will be no problem lines or use a function delegate to manage the instantiation and error handling. 我建议避免使用单行方法,除非您完全确定不会出现问题行或使用函数委托来管理实例化和错误处理。

Use SelectMany . 使用SelectMany

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM