使用Linq确定Uri列表是否是另一个Uri的基础
我想构建一个方法,确定给定的URL是否是列表中多个URL之一的子URL。我曾想过使用Linq实现这一点,但语法似乎超出了我的理解范围。这是我尝试过的,我希望isChild==true使用Linq确定Uri列表是否是另一个Uri的基础,linq,Linq,我想构建一个方法,确定给定的URL是否是列表中多个URL之一的子URL。我曾想过使用Linq实现这一点,但语法似乎超出了我的理解范围。这是我尝试过的,我希望isChild==true List<Uri> ProductionUriList = new List<Uri>(){ new Uri(@"https://my.contoso.com/sites/Engineering",UriKind.Absolute), new Uri(@"https://my
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)));
运行时错误显示:
方法的类型参数
'System.Linq.Enumerable.SelectManySystem.Collections.Generic.IEnumerable,
System.Func>'
无法从用法推断。尝试指定类型参数
明确地说
要确定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;
如果只想检查集合上的布尔条件,可以使用任意运算符:
var isChild = ProductionUriList.Any(p => p.IsBaseOf(new Uri("https://my.contoso.com/sites/China/Site1", UriKind.Absolute)));
var isChild = ProductionUriList.Select(p => p.IsBaseOf(new Uri("https://my.contoso.com/sites/China/Site1", UriKind.Absolute)).Count > 0;
关于您的错误:selectmany运算符需要一个委托返回您未提供的IEnumerable。你把select和selectmany混为一谈了。如果选择select作为linq运算符,则可以对结果进行计数>0,这将给出与使用any运算符相同的结果:
var isChild = ProductionUriList.Any(p => p.IsBaseOf(new Uri("https://my.contoso.com/sites/China/Site1", UriKind.Absolute)));
var isChild = ProductionUriList.Select(p => p.IsBaseOf(new Uri("https://my.contoso.com/sites/China/Site1", UriKind.Absolute)).Count > 0;
第二个答案是错误的,请参阅下面我的Henrik Cookes第二个答案以了解正确的计数。