2

我的输入数据是下面的行列表,称之为行

author1::author2::author3 - 标题

我创建了一个提取作者和标题的函数:

ExtractNameAndAuthors(string line, out string title, IList<string> authors)

我现在想以如下形式使用 Linq 创建一个查找 (ILookup) 对象:

键:标题
值:作者列表

有人真正精通Linq吗?

4

3 回答 3

4

LINQ 通常不能很好地处理out参数。你可以这样做,但通常最好避免它。与其通过参数传递数据,不如创建一个保存标题和作者列表的新类型,以便ExtractNameAndAuthors可以返回该类型的实例:

public class Book
{
    public Book(string title, IList<string> authors)
    {
        Title = title;
        Authors = authors;
    }

    public string Title{get;private set;}
    public IList<string> Authors{get; private set;}
}

一旦你有了它,并进行了ExtractNameAndAuthors相应的修改,你可以这样做:

var lookup = lines.Select(line => ExtractNameAndAuthors(line))
    .ToLookup(book => book.Title, book => book.Authors);
于 2013-04-17T14:38:14.977 回答
4
var list = new []{"author1::author2::author3 - title1",
                  "author1::author2::author3 - title2",};

var splited = list.Select(line => line.Split('-'));   

var result = splited
   .ToLookup(line => line[1], 
             line => line[0].Split(new[]{"::"}, StringSplitOptions.RemoveEmptyEntries));
于 2013-04-17T14:38:26.220 回答
1
public class Book
{
    public Book(string line)
    {
        this.Line = line;
    }

    public string Line { get; set; }
    public string[] Authors
    {
        get
        {
            return Line.Substring(0, Line.IndexOf("-") - 1).Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
        }
    }
    public string Name
    {
        get
        {
            return Line.Substring(Line.IndexOf("-") + 1);
        }
    }
}

static void Main(string[] args)
{
    var books = new List<Book>
    {
        new Book("author1::author2::author3 - title1"),
        new Book("author1::author2 - title2")            
    };

    var auth3books = books.Where(b => b.Authors.Contains("author3"));
}
于 2013-04-17T14:44:51.337 回答