这里我有一个简单的例子,在字符串列表中查找一个项。通常我使用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在列表中查找项目吗?如果这是可能的,怎么做?


当前回答

你可以使用FirstOfDefault和Where LINQ扩展从IEnumerable中获取MessageAction类。芮米

var action = Message.Actions.Where(e => e.targetByName == className).FirstOrDefault<MessageAction>();

在哪里

List<MessageAction> Actions { get; set; }

其他回答

这种方法更简单、更安全

var lOrders = new List<string>();

bool insertOrderNew = lOrders。Find(r => r == "1234") == null ?True: false

如果我们需要从列表中找到一个元素,那么我们可以使用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); 

还有一种检查List<string>中元素是否存在的方法:

var result = myList.Exists(users => users.Equals("Vijai"))

你想在对象列表中搜索一个对象。

这将帮助您在Linq列表搜索中获得第一个或默认值。

var item = list.FirstOrDefault(items =>  items.Reference == ent.BackToBackExternalReferenceId);

or

var item = (from items in list
    where items.Reference == ent.BackToBackExternalReferenceId
    select items).FirstOrDefault();

你想要列表中的项目还是实际的项目本身(假设项目本身)。

这里为你提供了一些选择:

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);