[英]LINQ Select Multiple Elements from a List<object[]>
我有一個列表,其中填充了數據庫中的數據。 對象數組在填充時有10個元素,我想執行一個LINQ Select語句,該語句返回僅包含2個元素的List<object[]>
。 如何選擇這些元素1和2。
我已經嘗試了以下對元素0起作用的方法,但是如何獲得元素0和元素1呢?
var resultDistinct = result.Select(p => p.GetValue(0)).Distinct();
var resultDistinct2 = result.Select(p => p.ElementAt(0)).Distinct();
您可以為此使用匿名對象。
var items = result.Select(p => new { ValueA = p.GetValue(0), ValueB = p.GetValue(1) });
然后訪問每個項目
foreach(var item in items)
{
var valueA = item.ValueA;
var valueB = item.ValueB;
}
您可以使用Take
擴展方法:
items.Take(x);
這將返回集合的前x
項目。
如果要跳過某些元素,可以在調用Take
之前使用Skip(x)
。 這兩種方法通常用於分頁。
如果您想與眾不同,然后再為2,
result.Select(p => p).Distinct().Take(2);
如果只有2那么
result.Take(2);
private class Foo
{
public int Item1;
public int Item2;
public int Item3;
}
static void Main(string[] args)
{
List<Foo> foos = new List<Foo>
{
new Foo() { Item1 = 1, Item2 = 2, Item3 = 3 },
new Foo() { Item1 = 4, Item2 = 5, Item3 = 6 },
new Foo() { Item1 = 7, Item2 = 8, Item3 = 9 }
};
// Create a list of lists where each list has three elements corresponding to
// the values stored in Item1, Item2, and Item3. Then use SelectMany
// to flatten the list of lists.
var items = foos.Select(f => new List<int>() { f.Item1, f.Item2, f.Item3 }).SelectMany(item => item).Distinct();
foreach (int item in items)
Console.WriteLine(item.ToString());
Console.ReadLine();
}
請參閱: https : //nickstips.wordpress.com/2010/09/16/linq-selecting-multiple-properties-from-a-list-of-objects/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.