我有一个看起来像的 XML 文档
<recipes>
<ingredient value"1">APPLE</ingredient>
<ingredient value"2">BANANA</ingredient>
<ingredient value"3">APPLE ORANGE</ingredient>
<ingredient value"4">APPLE BANANA</ingredient>
<ingredient value"5">APPLE STRAWBERRY</ingredient>
<ingredient value"6">GRAPES</ingredient>
</recipes>
现在用户输入一些字符串,例如Apple Grapes Banana
。我按字母顺序对其进行排序,并尝试通过使用字符串操作递归地消除最后一个单词来将其与其中一个值匹配。但我确信在 Linq 中有一种更有效的方法可以做到这一点。我希望查询返回 XML 中最接近的匹配项<ingredient value"4">APPLE BANANA</ingredient>
。
string str = "APPLE BANANA GRAPES"; // user input arranged by ascending alphabet and capitalized
XDocument xdoc = XDocument.Load(above xml);// gets above xml
var h = xdoc.Root.Elements("ingredient").FirstOrDefault(u => u.Value == str);//recurse these steps
if (h == null)
{
str = str.Remove(str.LastIndexOf(" "));//recurse these steps
}
//check if str matches any value;
//if not remove last word from str and check again;