我有一个按元素的 Name 属性排序的元素集合。我需要在保持顺序的同时将新元素插入集合中。我正在寻找一种简洁的 LINQ 方法来做到这一点。我的代码如下。 “this.Children”是集合,“d”是我需要插入的新元素。需要两次遍历集合才能找到插入点。有没有办法从 First() 扩展方法获取索引? (请不要建议使用 foreach,我知道:),我正在学习 LINQ)。
谢谢!
康斯坦丁
var v = this.Children.FirstOrDefault(x => string.Compare(x.Name, d.Name) > 0);
int index = this.Children.IndexOf(v);
if (index < 0)
{
this.children.Add(d);
}
else
{
this.Children.Insert(index, d);
}
是的,使用超载的Select http://msdn.microsoft.com/en-us/library/bb534869.aspx其中包括索引和值:
var pair = this.Children
.Select((value, index) => new { value, index })
.FirstOrDefault(x => string.Compare(x.value.Name, d.Name) > 0);
if (pair == null)
{
Children.Add(d);
}
else
{
Children.Insert(pair.index, d);
}
请注意,这仍然是低效的 - 如果您已经知道值已排序,则可以使用二分切来找出插入索引。在不知道类型的情况下很难给出示例代码Children
虽然……已经有List<T>.BinarySearch http://msdn.microsoft.com/en-us/library/w4e7fxsh.aspx and Array.BinarySearch http://msdn.microsoft.com/en-us/library/system.array.binarysearch.aspx.
学习 LINQ 令人钦佩 - 但当使用 LINQ 不是最好的方法时学习也很重要:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)