假设我有两个列表List<NewTile>
和List<OldTile>
。 List<OldTile>
总是包含比List<NewTile>
更多的项目。
public class NewTile
{
public Uri Navigation { get; set; }
public string Info { get; set; }
}
public class OldTile
{
public String Scheme { get; set; }
public string Status { get; set; }
}
例如,
Navigation
属性始终包含Scheme
字符串,这就是这两个列表之间的项目关联方式。Scheme = "wikipedia"
Navigation = "/Pages/BlankPage.xaml?Scheme=wikipedia"
我想从
List<NewTile>
获取所有项目,这些项目的Navigation属性与Scheme
的List<OldTile>
字符串都不匹配。如何使用LINQ做到这一点? 最佳答案
IEnumerable<NewTile> filtered = newTiles // get me all new tiles...
.Where(
newTile => // ...for which it's true that...
oldTiles
.All( // ...for all the old tiles...
oldTile =>
!newTile.Navigation.OriginalString.EndsWith("?Scheme=" + oldTile.Scheme)));
// ...this condition is met.
我相信,此方法的计算复杂度为O(n2),因此在处理大型列表时要格外小心。
编辑:
至于解析参数(不使用HttpUtility),可以使用Uri和Regex完成。
诀窍在于,由于您只有相对的
Uri
,因此需要在现场创建一个绝对值。以下方法对我有用:
string GetScheme(string relativeUri)
{
string fakeSite = "http://fake.com"; // as the following code wouldn't work on relative Uri!
Uri uri = new Uri(fakeSite + relativeUri);
string query = uri.Query;
string regexPattern = Regex.Escape("?Scheme=") + "(?<scheme>\\w+)";
Match match = new Regex(regexPattern).Match(query);
if (match.Captures.Count > 0)
{
return match.Groups["scheme"].Value;
}
return String.Empty;
}