LINQ通过字符串数组列表搜索特定字符串 [英] LINQ search though a list of string arrays for a particular string

查看:157
本文介绍了LINQ通过字符串数组列表搜索特定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组列表:

I have a list of string arrays:

List<String[]> listOfStringArrays = something;

我需要从集合中选择所有值等于列表中任何字符串数组的第0个索引处的字符串的对象.

I need to select all objects from a collection that have a value which is equal to the string at the 0th index of any string array in the list.

例如,如果我只有一个简单的字符串列表,则声明为:

For example, if I just had a simple list of strings, declared as:

List<String> listOfStrings = something;

我会这样做:

var query = someCollection.Where(x => listOfStrings.Contains(x.id_num))

但是显然,使用字符串数组列表并不是那么简单.

But obviously it's not as simple with a list of string arrays.

我知道我可以轻松地遍历字符串数组列表,并创建一个具有0th值的简单字符串列表,如下所示:

I know that I can easily just iterate through the list of string arrays and create a simple list of strings with the 0th value, like this:

List<String[]> listOfStringArrays = something;
List<String> listOfValues = new List<String>();

foreach (string[] s in listOfStringArrays)
    listOfValues.Add(s[0]);

var query = someCollection.Where(x => listOfValues.Contains(x => x.id_num);

但是,我真的很想避免这种情况,并尝试将其编写为一个衬里而不引入额外的列表和循环.

But would really like to avoid this and am trying to write it as a one liner without introducing extra lists and loops.

推荐答案

您可以将其全部放入一个查询中:

You can put it all into one query:

someCollection.Where(x => listOfValues.Select(y => y[0]).Contains(x => x.id_num);

但是它将反复遍历listOfValues.

我宁愿使用HashSet<string>来使其更快:

I would rather go with HashSet<string> to make it faster:

var set = new HashSet<string>(listOfValues.Select(y => y[0]));
someCollection.Where(x => set.Contains(x));

这篇关于LINQ通过字符串数组列表搜索特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆