[英]Linq - Create a set-length list with default values where empty
我知道這應該很容易做到,但是假設在我的C#應用程序中,我有一個IEnumerable<string>
並且我需要使用null
s創建一個更大的可枚舉的額外值。
因此,舉例來說,假設我的enumerable具有12個元素,並且我需要創建一個包含24個元素的最終列表(因此,最后12個元素為null)。 我知道我可以使用for循環對其進行編程,但是必須有一種使用Linq進行此操作的簡單方法,而且我不確定該使用哪種方法。
謝謝!!
我建議使用Enumerable.Range或Repeat
var list = yourList.Concat(Enumerable.Range(1, 24).Select(i => null)).Take(24);
var list = yourList.Concat(Enumerable.Repeat(null, 24)).Take(24);
再說一次 。
List<string> list = new List<string>() { "one", "two", "three" };
list.AddRange(Enumerable.Repeat((string)null, 10));
您可以這樣做以獲得24個元素。
list.AddRange(Enumerable.Repeat((string)null, 24-list.Count()));
這是我想到的第一件事:
currentList = currentList.Concat( // build onto your current list
Enumerable.Range(1, 24 - currentList.Count()) // number of elements needed
.Select(i => (string)null)); // what you want the element to be
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.