2014-07-25 136 views
0

你好,我是新來的LINQ和拉姆達Linq查詢,選擇一切從一個列出了與另一個列表

我有兩個列表

fl.LocalOpenFiles ... 
List<string> f.... 

有一個屬性(字符串的字符串開頭財產),例如以指數0

fl.LocalOpenFiles[0].Path 

我想選擇所有從第一清單fl.LocalOpenFiles其中fl.LocalOpenFiles.Path開始從字符串

我終於得到這個...

List<LocalOpenFile> lof = new List<LocalOpenFile>(); 
lof = fl.LocalOpenFiles.Join(
    folders, 
    first => first.Path, 
    second => second, 
    (first, second) => first) 
    .ToList(); 

但它只是選擇符合要求first.Path == second文件夾和我不能找到一個辦法讓我想這是一件好事會議這種「題庫」數據要求:

f[<any>] == fl.LocalOpenFiles[<any>].Path.Substring(0, f[<any>].Length) 

另一個實施例...

List<string> f = new List<string>{ "abc", "def" }; 
List<LocalOpenFile> lof = new List<LocalOpenFile>{ 
    new LocalOpenFile("abc"), 
    new LocalOpenFile("abcc"), 
    new LocalOpenFile("abdd"), 
    new LocalOpenFile("defxsldf"),)} 

    // Result should be 
    // abc 
    // abcc 
    // defxsldf 

我希望我的理解的方式解釋吧:) 謝謝您的幫助

回答

0

您可以使用常規where,而不是加入,這將給你在選擇標準更直接的控制;

var result = 
    from file in lof 
    from prefix in f 
    where file.Path.StartsWith(prefix) 
    select file.Path; // ...or just file if you want the LocalOpenFile objects 

請注意,匹配多個前綴的文件可能會多次出現。如果這是一個問題,您可以添加一個電話到Distinct以消除重複。

編輯:
如果你 - 因爲它似乎在這種情況下 - 只想知道匹配的路徑,而不是前綴它匹配(即你只需要在這種情況下,從一個收集數據),我會去代替@ har07的Any解決方案。

1

你的意思是這樣的:

List<LocalOpenFile> result = 
     lof.Where(file => f.Any(prefix => file.Path.StartsWith(prefix))) 
      .ToList(); 
+1

+1,任何肯定更緊湊的是,雖然變量的命名還有待改進。 –

相關問題