繁体   English   中英

通过 LINQ 在列表中查找项目

[英]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 查找列表中的项目吗? 如果可能,如何?

有几种方法(请注意,这不是一个完整的列表)。

  1. Single将返回单个结果,但如果没有找到或多个(可能是也可能不是您想要的),则会抛出异常:

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

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

  1. 哪里将返回符合您的条件的所有项目,因此您可能会获得一个包含一个元素的 IEnumerable<string> :

     IEnumerable<string> results = myList.Where(s => s == search);
  2. 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();

此搜索将查找将返回的第一个或默认值。

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

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

这将帮助您在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM