2013-04-17 36 views
2

我輸入的數據是類似下面的線的列表,叫它行如何使用Linq從列表中創建查找?

作者1 :: author2 :: author3 - 標題

我創建的提取作者的功能和標題:

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

我現在想創建形式使用LINQ查詢(ILookup)對象:

關鍵:標題
價值:作者

有人在LINQ的真正流暢的名單?

+0

創建一個小的類屬性鍵,值和'ExtractNameAndAuthors'返回。那麼你可以在Linq中輕鬆使用它 – I4V

回答

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); 
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)); 
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")); 
}