[英]How to get first object out from List<Object> using Linq
我在 c# 4.0 中有以下代碼。
//Dictionary object with Key as string and Value as List of Component type object
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>();
//Here I am trying to do the loping for List<Component>
foreach (List<Component> lstComp in dic.Values.ToList())
{
// Below I am trying to get first component from the lstComp object.
// Can we achieve same thing using LINQ?
// Which one will give more performance as well as good object handling?
Component depCountry = lstComp[0].ComponentValue("Dep");
}
嘗試:
var firstElement = lstComp.First();
您也可以使用FirstOrDefault()
以防lstComp
不包含任何項目。
http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx
編輯:
獲取Component Value
:
var firstElement = lstComp.First().ComponentValue("Dep");
這將假設lstComp
有一個元素。 另一種更安全的方法是......
var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null)
{
var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}
[0]
或.First()
無論發生什么都會給你相同的性能。
但是您的Dictionary
可能包含IEnumerable<Component>
而不是List<Component>
,然后您就不能使用[]
運算符。 這就是差異巨大的地方。
因此,對於您的示例,這並不重要,但是對於此代碼,您無法選擇使用 First():
var dic = new Dictionary<String, IEnumerable<Component>>();
foreach (var components in dic.Values)
{
// you can't use [0] because components is an IEnumerable<Component>
var firstComponent = components.First(); // be aware that it will throw an exception if components is empty.
var depCountry = firstComponent.ComponentValue("Dep");
}
你可以做
Component depCountry = lstComp
.Select(x => x.ComponentValue("Dep"))
.FirstOrDefault();
或者,如果您想在整個值字典中使用它,您甚至可以將其綁定回鍵
var newDictionary = dic.Select(x => new
{
Key = x.Key,
Value = x.Value.Select( y =>
{
depCountry = y.ComponentValue("Dep")
}).FirstOrDefault()
}
.Where(x => x.Value != null)
.ToDictionary(x => x.Key, x => x.Value());
這會給你一本新字典。 您可以訪問這些值
var myTest = newDictionary[key1].depCountry
你也可以使用這個:
var firstOrDefault = lstComp.FirstOrDefault();
if(firstOrDefault != null)
{
//doSmth
}
首先嘗試獲取所有列表,然后是您想要的元素(在您的情況下說第一個):
var desiredElementCompoundValueList = new List<YourType>();
dic.Values.ToList().ForEach( elem =>
{
desiredElementCompoundValue.Add(elem.ComponentValue("Dep"));
});
var x = desiredElementCompoundValueList.FirstOrDefault();
要直接獲取第一個元素值而不需要大量的 foreach 迭代和變量賦值:
var desiredCompoundValue = dic.Values.ToList().Select( elem => elem.CompoundValue("Dep")).FirstOrDefault();
查看兩種方法之間的區別:在第一種方法中,您通過 ForEach 獲取列表,然后是您的元素。 第二,你可以直接獲得你的價值。
相同的結果,不同的計算 ;)
對於 linq 表達式,您可以像這樣使用:
List<int> list = new List<int>() {1,2,3 };
var result = (from l in list
select l).FirstOrDefault();
對於 lambda 表達式,您可以像這樣使用
List list = new List() { 1, 2, 3 }; int x = list.FirstOrDefault();
我這樣做。
List<Object> list = new List<Object>();
if(list.Count>0){
Object obj = list[0];
}
有很多這樣的方法:
.First .FirstOrDefault .Single .SingleOrDefault
選擇最適合您的。
var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));
我會喜歡這樣:
//Dictionary object with Key as string and Value as List of Component type object
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>();
//from each element of the dictionary select first component if any
IEnumerable<Component> components = dic.Where(kvp => kvp.Value.Any()).Select(kvp => (kvp.Value.First() as Component).ComponentValue("Dep"));
但僅當確定列表僅包含 Component 類或子類的對象時
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.