2014-09-22 52 views
0

我想要構建一個方法來確定給定的URL是否是列表中某個URL的子節點之一。我想用Linq來解決這個問題,但是這個語法似乎超出了我的理解範圍。這是我所嘗試的,我期望isChild == true。使用Linq來確定Uris的列表是否是另一個Uri的基址

List<Uri> ProductionUriList = new List<Uri>(){ 
    new Uri(@"https://my.contoso.com/sites/Engineering",UriKind.Absolute), 
    new Uri(@"https://my.contoso.com/sites/APAC",UriKind.Absolute), 
    new Uri(@"https://my.contoso.com/sites/China",UriKind.Absolute), 
    new Uri(@"https://my.contoso.com/sites/EMEA",UriKind.Absolute), 
    new Uri(@"https://my.contoso.com/sites/India",UriKind.Absolute), 
    new Uri(@"https://my.contoso.com/sites/Mexico",UriKind.Absolute), 
    new Uri(@"https://my.contoso.com/sites/SamCam",UriKind.Absolute), 
    new Uri(@"https://my.contoso.com/sites/USA",UriKind.Absolute), 
}; 


var isChild = 
     ProductionUriList.SelectMany (p => p.IsBaseOf(new Uri("https://my.contoso.com/sites/China/Site1",UriKind.Absolute))); 

運行時錯誤說:

The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

回答

0

如果你只是想t一個布爾條件O檢查一組,你可以使用任何運營商:

var isChild = ProductionUriList.Any(p => p.IsBaseOf(new Uri("https://my.contoso.com/sites/China/Site1", UriKind.Absolute))); 

關於你的錯誤:運營商的SelectMany預計,返回IEnumerable的,你不提供委託。你正在混合select和selectmany。

var isChild = ProductionUriList.Select(p => p.IsBaseOf(new Uri("https://my.contoso.com/sites/China/Site1", UriKind.Absolute)).Count > 0; 
+0

第二個「答案」是錯誤的,看到我的(亨裏克Cookes):如果選擇選擇爲LINQ操作符,你可以爲使用任何運營商做的結果計數> 0,這將產生相同的結果第二個答案的答案在下面進行正確計數。 – 2014-09-23 05:13:05

0

要確定的URI是一個或一個以上的孩子:

var isChild = ProductionUriList.Any(p => p.IsBaseOf(newUri("https://my.contoso.com/sites/China/Site1",UriKind.Absolute))); 

要確定該URI是隻有一個孩子:

var isChild = ProductionUriList.Count(p => p.IsBaseOf(newUri("https://my.contoso.com/sites/China/Site1",UriKind.Absolute))) == 1; 
相關問題