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


当前回答

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

这将帮助您在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();

其他回答

IndexOf怎么样?

搜索指定对象并返回列表中第一个出现项的索引

例如

> var boys = new List<string>{"Harry", "Ron", "Neville"};  
> boys.IndexOf("Neville")  
2
> boys[2] == "Neville"
True

注意,如果该值没有出现在列表中,则返回-1

> boys.IndexOf("Hermione")  
-1

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

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

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

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

在哪里

List<MessageAction> Actions { get; set; }

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

试试下面的代码:

return context.EntitytableName.AsEnumerable().Find(p => p.LoginID.Equals(loginID) && p.Password.Equals(password)).Select(p => new ModelTableName{ FirstName = p.FirstName, UserID = p.UserID });