【问题标题】:Get data from IEnumerable using IEnumerable<string> as a parameter [closed]使用 IEnumerable<string> 作为参数从 IEnumerable 获取数据
【发布时间】:2017-04-15 16:35:36
【问题描述】:

我有一个类型的类

public class One
{
    public string firstString { get; set; }
    public string secondString { get; set; }
}

还有 IEnumerable:

IEnumerable<One> firstIEnumerable;

在程序执行期间,我得到另一个 IEnumerable,

IEnumerable<string> secondIEnumerable = List<string>.Where(...);

我想要的是使用firstIEnumerablefirstString 成员和来自secondIEnumerable 的任何值之间的相等性来请求firstIEnumerablesecondString

我想象一个这样的命令:

IEnumerable<string> thirdIEnumerable =
    firstIEnumerable.Where(m=>m.firstString == secondIEnumerable.? ? ? ? ?).secondString; 

但它不能编译。

【问题讨论】:

  • 如果没有具体的例子,真的很难说出你想要达到的目标。请张贴minimal reproducible example,其中包含示例输入和您想要实现的输出。请记住,两者都是 sequences - 您是否尝试将 每个 项与另一个项进行匹配?
  • 我已将问题编辑得更直接、更清晰。

标签: c# linq ienumerable


【解决方案1】:

如果第二个可枚举是一个长序列,您可能(检查基准)最好执行两次并创建一个哈希集,而不是执行 O(N * M) 算法。 O(N * M) 一个将是:

first.Where(x => second.Contains(x.firstString)).Select(x => x.secondString)

使用哈希集:

var hashSet = new HashSet<string>(second);
first.Where(x => hashSet.Contains(x.firstString)).Select(x => x.secondString)

第二个选项可能会在大多数情况下提供更好的性能。

【讨论】:

    【解决方案2】:

    如果我理解正确,您想为每个项目选择secondString firstString 包含secondIEnumerable

    var result = firstIEnumerable.Where(item => secondIEnumerable.Contains(item.firstString))
                                 .Select(item => item.secondString);
    

    查询语法可能更好:

    var result = from item in firstIEnumerable
                 where secondIEnumerable.Contains(item.firstString)
                 select item.secondString;
    

    【讨论】:

      【解决方案3】:

      也许你可以用这个:

              IEnumerable<string> thirdEnumerable =   from firstItem in firstIEnumerable
                                                      from secondItem in secondIEnumerable
                                                      where firstItem.firstString == secondItem
                                                      select firstItem.firstString;
      

      或者这种内联方式:

      IEnumerable<string> thirdEnumerable2 = firstIEnumerable.Select(x => x.firstString).Intersect(secondIEnumerable);
      

      【讨论】:

        猜你喜欢
        • 2013-01-25
        • 1970-01-01
        • 1970-01-01
        • 2010-10-16
        • 2013-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多