[英]Get items from list where index not equal to an int using LINQ
我在List
有項目,我想獲取所有索引不等於某物的項目,
說這是按鈕List<Button>
。 我如何使用類似於以下內容的index
獲取那些帶有索引的按鈕。
var buttons = buttonList.Where(b => b<indexOfbutton> != index);
更新:
我正在嘗試在一行中獲取<indexOfButton>
。 因此,我假設還有另一個linq查詢來從buttonList獲取按鈕索引?
最終目標是獲取不包含相關索引的List。
您可以在lambda表達式中指定索引 ,因為Where
方法存在另一個重載,該重載采用Func<TSource, int, bool>
:
System.Func<TSource, Int32, Boolean>
測試條件中每個源元素的功能; 函數的第二個參數表示源元素的索引。
var buttons = buttonList.Where((b,idx) => idx != index);
您也可以為此編寫擴展方法:
public static class Extensions
{
public static IEnumerable<T> SkipIndex<T>(this IEnumerable<T> source, int index)
{
int counter = 0;
foreach (var item in source)
{
if (counter != index)
yield return item;
counter++;
}
}
}
並使用它:
var buttons = buttonList.SkipIndex(index).ToList();
如果要獲取帶有其索引的按鈕:
var buttons = buttonList
.Select((b,idx) => new { Button = b, Index = idx })
.Where(x => x.Index != index)
.ToList();
這將返回一個匿名類型列表,其中包含兩個屬性,其中一個是您的按鈕,另一個是它的索引。
如果我有扔掉的列表(如果我不需要原始列表,而只有沒有元素的列表),而buttonList是IList<>
,我將使用類似
buttonList.RemoveAt(index);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.