using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Comparer.csd
{
class Program
{
/* Confusion is regarding how ToList() method works. Does it do the deep copy or shallow copy??
/**********OUTPUT
a a b
a b c
a c a
-----------------
a a b
a c a
-----------------
1
2
3
OUTPUT ENDS************/
static void Main(string[] args)
{
List<test> list = new List<test>();
list.Add(new test("a", "b", "c"));
list.Add(new test("a", "c", "a"));
list.Add(new test("a", "a", "b"));
/// sort the list based on first name and last name
IEnumerable<test> soretedCollection = from t in list
orderby t._fname ascending, t._mname ascending
select t;
Print(soretedCollection);
/// remove the first object from the list
list.RemoveAt(0);
/// print the list .
/// Removal of the item from the list is reflected here so I guess sorted collection and list both
/// are refering the same data structure
/// what if I will do
/// list = soretedCollection.ToList<test>(); /// is it going to change the reference of the list if some other object
/// is holding the reference??
Print(soretedCollection);
Dictionary<int, int> dic = new Dictionary<int, int>();
dic.Add(1, 1);
dic.Add(2, 1);
dic.Add(3, 1);
List<int> keys = dic.Keys.ToList<int>();
/// remove the dictionary entry with key=2
dic.Remove(2);
/// how come this time it did not remove the second item becuase it is removed from the dictionary.
for (int i = 0; i < keys.Count; ++i)
{
Console.WriteLine(keys[i].ToString());
}
Console.Read();
}
static void Print(IEnumerable<test> list)
{
foreach (test t in list)
{
t.Print();
}
Console.WriteLine("---------------------");
}
}
}
Q
LINQ相關問題
0
A
回答
4
調用.ToList()
力量渴望執行完整枚舉的 - 這樣做的結果是從原來的枚舉一個單獨的列表,所以.ToList()
後的任何更改將不在該列表中得到反映。這個列表中的實際項目與@Johannes Rudolph指出的原始枚舉中的相同(相同的對象引用) - 所以是的,這是一個淺拷貝。
的IEnumerable<test>
雖然將懶洋洋地在源集合執行 - 只有當你積極地列舉項目將枚舉創建一個枚舉取源集合,因爲它是在這一點上(通過使用foreach
或.ToList()
IE)及時 - 這意味着如果在創建枚舉器之前底層集合中存在更改,這些將會反映在枚舉中。
3
ToList
將始終創建列表的淺表副本,這是返回的列表將引用相同對象作爲源IEnumerable
做,但返回的列表是源代碼的副本。
參見MSDN。
相關問題
- 1. 堆相關問題
- 2. viewWillAppear相關問題
- 3. TableLayout相關問題
- 4. Pearson相關問題
- 5. stackoverflow「相關問題」
- 6. SSL相關問題
- 7. StringBuilder相關問題
- 8. MVC相關問題
- 9. StringBuilder相關問題
- 10. setContentsURL相關問題
- 11. jquery相關問題
- 12. 與C++相關的問題有問題
- 13. DOM相關的問題和問題
- 14. 與LINQ和對象引用相關的問題
- 15. 按列表中的問題排序(linq相關)
- 16. Cython - gil相關問題
- 17. Kohana鏈接相關問題
- 18. 與@property相關的問題
- 19. 與IndexOutOfRangeException相關的問題
- 20. 複製相關問題,
- 21. Stackoverflow的相關問題
- 22. 與UIButton相關的問題
- 23. JQGrid,搜索相關問題
- 24. SQL連接相關問題
- 25. 的JavaScript相關問題
- 26. Windows DPI相關問題
- 27. 問題與相關實體
- 28. 相關選擇框問題
- 29. SQL Server相關問題
- 30. MySQL查詢相關問題:
完美...懂了...謝謝 – mchicago 2011-03-09 03:31:50