我的输入数据是列表的行,如下所示,称之为行
author1 :: author2 :: author3 - title
我创建了一个提取作者和标题的函数:
ExtractNameAndAuthors(string line, out string title, IList<string> authors)
我现在想要以下列形式使用Linq创建一个查找(ILookup)对象:
键:标题
值:作者列表
任何人都能熟练使用Linq?
答案 0 :(得分: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);
答案 1 :(得分: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));
答案 2 :(得分: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"));
}