linq方式按顺序插入元素

ako*_*nsu 1 c# linq

我有一个按元素名称属性排序的元素集合.我需要在维护订单的同时将新元素插入到集合中.我正在寻找一种简洁的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);
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

是的,使用包含索引和值的重载Select:

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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这仍然是低效的 - 如果您已经知道值已排序,则可以使用二进制切块来查找插入索引.在不知道类型的情况下很难给出示例代码Children...已经存在List<T>.BinarySearchArray.BinarySearch.

学习LINQ是令人钦佩的 - 但是当使用LINQ不是最好的方法时学习也很重要:)