这里我有一个简单的例子,在字符串列表中查找一个项。通常我使用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的方法:

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,

and

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 item = list.FirstOrDefault(items =>  items.Reference == ent.BackToBackExternalReferenceId);

or

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

下面是一种重写你的方法来使用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,

and

GetItemIndex("notthere")将返回-1。

参考:linqsamples.com

这种方法更简单、更安全

var lOrders = new List<string>();

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

如果你想要元素的索引,这将做到:

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

你不能在第一遍就消去。

注意,如果项目不存在,这将抛出。这通过使用可空int型来解决问题:

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;

不要忘记在这些情况下检查列表是否为空。

或者使用(list ??Enumerable.Empty<string>())而不是list。