我昨天正在研究一个方法,并遇到了一些奇怪的问题,这里是代码的笨拙版本:基本上问题是OrderBy应用于Bar.PopulateList方法不是持久的。将对象传递给方法,然后调用该对象的扩展方法
class Foo
{
List MyObjects;
public void PopulateMyObjects()
{
//Items are added to my list but the OrderBy is not persisting.
Bar.PopulateList(MyObjects);
}
}
class Bar
{
public static int PopulateList(List theList)
{
foreach(var in WebSerbiceCall)
{
theList.Add(var);
}
// the OrderBy call only sorts 'theList' in the context of this method.
// When I return from this method theList has been populated but the Ordering has
// reverted back to the order that the items were added to the list.
theList.OrderBy(obj => obj.ID);
return theList.Count;
}
}
现在,如果我更新代码,并添加ref关键字按下面的所有作品: 例如public static int PopulateList(ref List List) and Bar.PopulateList(ref MyObjects);
任何人都可以启发我吗?我以为对象总是被ref引用? OrderBy是一种扩展方法吗?
感谢,慈安
有序枚举是否与未排序列表具有相同数量的元素? – dtb 2010-12-02 00:29:28
OrderBy上面有代码:theList.Add(var);所以我不认为这是可以假设的。 – jwwishart 2010-12-02 00:33:30
但OrderBy不添加或删除任何元素,所以`theList.OrderBy(obj => obj.ID).Count()`应该等于`theList.Count`,否? – dtb 2010-12-02 01:05:19