首页 文章

在LINQ中找到List中的项目?

提问于
浏览
200

这里我有一个简单的例子来查找字符串列表中的项目 . 通常我使用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 anonymous delegate
      string foundItem = _list.Find( delegate(string item) {
         found++;
         return string.Equals(search, item);
      });
      */
   }
   return found;
}

LINQ对我来说是新的 . 我很好奇我是否可以使用LINQ来查找列表中的项目?怎么可能?

12 回答

  • 70

    有几种方法(注意这不是一个完整的清单) .

    1)Single将返回单个结果,但如果找不到或多于一个(可能是或不是你想要的),将抛出异常:

    string search = "lookforme";
    List<string> myList = new List<string>();
    string result = myList.Single(s => s == search);
    

    注意 SingleOrDefault() 的行为相同,除了它将为引用类型返回null,或者为值类型返回默认值,而不是抛出异常 .

    2)Where将返回符合您条件的所有项目,因此您可以使用一个元素获得IEnumerable:

    IEnumerable<string> results = myList.Where(s => s == search);
    

    3)First将返回符合您条件的第一项:

    string result = myList.First(s => s == search);
    

    注意 FirstOrDefault() 的行为相同,除了它将为引用类型返回null,或者为值类型返回默认值,而不是抛出异常 .

  • 1

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

    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 .

    请注意,如果该项目不存在,则会抛出此值 . 这通过诉诸可空的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;
    

    并且不要忘记在任何这些情况下检查 null 的列表 .

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

    感谢Pavel帮助评论 .

  • 13

    如果它真的是 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));
    }
    
  • 2

    您想要列表中的项目还是实际项目本身(将假定项目本身) .

    以下是一些选项:

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

    这种方法更简单,更安全

    var lOrders = new List<string>();
    

    bool insertOrderNew = lOrders.Find(r => r == "1234") == null ? true : false

  • 1

    IndexOf怎么样?

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

    例如

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

    请注意,如果列表中未出现该值,则返回-1

    > boys.IndexOf("Hermione")  
    -1
    
  • 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"];
    

    因此,根据您正在做的事情,字典可能很有用 .

  • 6

    以下是重写方法以使用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

  • 0

    试试这段代码:

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

    如果我们需要从列表中找到一个元素,那么我们可以使用 FindFindAll 扩展方法,但它们之间存在细微差别 . 这是一个例子 .

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

    这将帮助您获取Linq列表搜索中的第一个或默认值

    var results = _List.Where(item => item == search).FirstOrDefault();
    

    此搜索将找到它将返回的第一个或默认值 .

  • 10

    You want to search an object in object list.

    这将帮助您获取Linq列表搜索中的第一个或默认值 .

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

    要么

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

相关问题