[英]Find an item in a list by LINQ
在這里,我有一個簡單的示例來查找字符串列表中的項目。 通常我使用for
循環或匿名委托來這樣做:
int GetItemIndex(string search)
{
int found = -1;
if ( _list != null )
{
foreach (string item in _list) // _list is an instance of List<string>
{
found++;
if ( string.Equals(search, item) )
{
break;
}
}
/* Use an anonymous delegate
string foundItem = _list.Find( delegate(string item) {
found++;
return string.Equals(search, item);
});
*/
}
return found;
}
LINQ 對我來說是新的。 我可以使用 LINQ 查找列表中的項目嗎? 如果可能,如何?
有幾種方法(請注意,這不是一個完整的列表)。
Single將返回單個結果,但如果沒有找到或多個(可能是也可能不是您想要的),則會拋出異常:
string search = "lookforme"; List<string> myList = new List<string>(); string result = myList.Single(s => s == search);
請注意, SingleOrDefault()
行為是相同的,除了它會為引用類型返回 null,或者為值類型返回默認值,而不是拋出異常。
哪里將返回符合您的條件的所有項目,因此您可能會獲得一個包含一個元素的 IEnumerable<string> :
IEnumerable<string> results = myList.Where(s => s == search);
First將返回符合您條件的第一個項目:
string result = myList.First(s => s == search);
請注意, FirstOrDefault()
行為相同,除了它會為引用類型返回 null 或為值類型返回默認值,而不是拋出異常。
如果你想要元素的索引,這將做到:
int index = list.Select((item, i) => new { Item = item, Index = i })
.First(x => x.Item == search).Index;
// or
var tagged = list.Select((item, i) => new { Item = item, Index = i });
int index = (from pair in tagged
where pair.Item == search
select pair.Index).First();
您無法在第一遍中擺脫 lambda。
請注意,如果該項目不存在,這將引發。 這通過使用可為空的整數來解決問題:
var tagged = list.Select((item, i) => new { Item = item, Index = (int?)i });
int? index = (from pair in tagged
where pair.Item == search
select pair.Index).FirstOrDefault();
如果你想要這個項目:
// Throws if not found
var item = list.First(item => item == search);
// or
var item = (from item in list
where item == search
select item).First();
// Null if not found
var item = list.FirstOrDefault(item => item == search);
// or
var item = (from item in list
where item == search
select item).FirstOrDefault();
如果要計算匹配項的數量:
int count = list.Count(item => item == search);
// or
int count = (from item in list
where item == search
select item).Count();
如果您想要所有匹配的項目:
var items = list.Where(item => item == search);
// or
var items = from item in list
where item == search
select item;
並且不要忘記在任何這些情況下檢查列表是否為null
。
或者使用(list ?? Enumerable.Empty<string>())
而不是list
。
如果它真的是一個List<string>
你不需要 LINQ,只需使用:
int GetItemIndex(string search)
{
return _list == null ? -1 : _list.IndexOf(search);
}
如果您正在尋找項目本身,請嘗試:
string GetItem(string search)
{
return _list == null ? null : _list.FirstOrDefault(s => s.Equals(search));
}
您想要列表中的項目還是實際項目本身(假設項目本身)。
這里有一堆選項供您選擇:
string result = _list.First(s => s == search);
string result = (from s in _list
where s == search
select s).Single();
string result = _list.Find(search);
int result = _list.IndexOf(search);
這種方法更簡單更安全
var lOrders = new List<string>();
bool insertOrderNew = lOrders.Find(r => r == "1234") == null ? true : false
IndexOf
怎么樣?
搜索指定的對象並返回列表中第一次出現的索引
例如
> var boys = new List<string>{"Harry", "Ron", "Neville"};
> boys.IndexOf("Neville")
2
> boys[2] == "Neville"
True
請注意,如果該值未出現在列表中,則返回 -1
> boys.IndexOf("Hermione")
-1
我曾經使用一個字典,它是某種索引列表,它會在我想要的時候准確地給我想要的東西。
Dictionary<string, int> margins = new Dictionary<string, int>();
margins.Add("left", 10);
margins.Add("right", 10);
margins.Add("top", 20);
margins.Add("bottom", 30);
例如,每當我希望訪問我的邊距值時,我都會處理我的字典:
int xStartPos = margins["left"];
int xLimitPos = margins["right"];
int yStartPos = margins["top"];
int yLimitPos = margins["bottom"];
因此,根據您在做什么,字典可能會很有用。
這是重寫您的方法以使用 LINQ 的一種方法:
public static int GetItemIndex(string search)
{
List<string> _list = new List<string>() { "one", "two", "three" };
var result = _list.Select((Value, Index) => new { Value, Index })
.SingleOrDefault(l => l.Value == search);
return result == null ? -1 : result.Index;
}
因此,調用它
GetItemIndex("two")
將返回1
,
和
GetItemIndex("notthere")
將返回-1
。
參考: linqsamples.com
試試這個代碼:
return context.EntitytableName.AsEnumerable().Find(p => p.LoginID.Equals(loginID) && p.Password.Equals(password)).Select(p => new ModelTableName{ FirstName = p.FirstName, UserID = p.UserID });
這將幫助您在 LINQ 列表搜索中獲取第一個或默認值
var results = _List.Where(item => item == search).FirstOrDefault();
此搜索將查找將返回的第一個或默認值。
如果我們需要從列表中查找一個元素,那么我們可以使用Find
和FindAll
擴展方法,但它們之間有細微的差別。 這是一個例子。
List<int> items = new List<int>() { 10, 9, 8, 4, 8, 7, 8 };
// It will return only one 8 as Find returns only the first occurrence of matched elements.
var result = items.Find(ls => ls == 8);
// this will returns three {8,8,8} as FindAll returns all the matched elements.
var result1 = items.FindAll(ls => ls == 8);
您想在對象列表中搜索一個對象。
這將幫助您在 Linq 列表搜索中獲得第一個或默認值。
var item = list.FirstOrDefault(items => items.Reference == ent.BackToBackExternalReferenceId);
要么
var item = (from items in list
where items.Reference == ent.BackToBackExternalReferenceId
select items).FirstOrDefault();
您可以使用帶有Where LINQ 擴展的 FirstOfDefault 從 IEnumerable 獲取 MessageAction 類。 雷米
var action = Message.Actions.Where(e => e.targetByName == className).FirstOrDefault<MessageAction>();
在哪里
List<MessageAction> Actions { get; set; }
檢查 List<string> 中元素是否存在的另一種方法:
var result = myList.Exists(users => users.Equals("Vijai"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.