【问题标题】:Linq to objects - Search collection with value from other collectionLinq to objects - 使用来自其他集合的值搜索集合
【发布时间】:2014-08-22 12:12:12
【问题描述】:

我已尝试在 SO 中搜索可能与我的情况相似的解决方案和问题。

我有 2 个对象集合:

public class BRSDocument
{
    public string IdentifierValue { get; set;}
}

public class BRSMetadata
{
    public string Value { get; set;}
}  

我从我的数据层填写列表:

List<BRSDocument> colBRSDocuments = Common.Instance.GetBRSDocuments();
List<BRSMetadata> colBRSMetadata = Common.Instance.GetMessageBRSMetadata();

我现在想在 colBRSDocuments 中找到一个对象,其中 x.IdentifierValue 等于 colBRSMetadata y.Value 中的一个对象。我只需要找到与 BRSMetadata 对象中的值匹配的 BRSDocument。

我使用了一个普通的 foreach 循环和一个简单的 linq 搜索来查找数据并在找到值时中断。我想知道是否可以完全使用 linq 完成搜索?

foreach (var item in colBRSMetadata)
{
    BRSDocument res = colBRSDocuments.FirstOrDefault(x => x.IdentifierValue == item.Value);

    if (res != null)
    {
        //Do work
        break;
    }
}

希望你们中的一些人能把我推向正确的方向......

【问题讨论】:

    标签: c# linq collections linq-to-objects


    【解决方案1】:

    为什么不加入?

    var docs = from d in colBRSDocuments
               join m in colBRSMetadata on d.IdentiferValue equals m.Value
               select d;
    

    如果只有一个,那么你可以这样做:

    var doc = docs.Single(); // will throw if there is not exactly one element
    

    如果您想返回两个对象,那么您可以执行以下操作:

    var docsAndData = from d in colBRSDocuments
                      join m in colBRSMetadata on d.IdentiferValue equals m.Value
                      select new
                      {
                          Doc = d,
                          Data = m
                      };
    

    然后你可以像这样访问:

    foreach (var dd in docsAndData)
    {
        // dd.Doc
        // dd.Data
    }
    

    【讨论】:

    • 我会试试 - 不知道你可以加入不相关的集合:)
    • 酷。试一试后报告!
    • 这个解决方案提供了所需的结果,并且对于程序员来说也非常易读。干得好!
    • 只是一个简单的问题:是否可以同时返回两个对象?用于查找 BRSDocument 的 BRSDocument 和 BRSMetadata 对象?
    • @Mötz 更新了答案。
    【解决方案2】:

    使用 Linq 吗? 像这样的东西应该可以完成这项工作:

    foreach (var res in colBRSMetadata.Select(item => colBRSDocuments.FirstOrDefault(x =>      x.IdentifierValue == item.Value)).Where(res => res != null))
            {
                //Do work
                break;
            }
    

    如果您只对第一项感兴趣,那么代码将是:

    var brsDocument = colBRSMetadata.Select(item => colBRSDocuments.FirstOrDefault(x => x.IdentifierValue == item.Value)).FirstOrDefault(res => res != null);
            if (brsDocument != null)
                //Do Stuff
    

    【讨论】:

    • 我确实尝试了这个解决方案,结果如预期 - 它还找到了我需要的对象。我试图避免使用 foreach 语法 - 所以 dav_i 提供的解决方案似乎最适合我的需求。感谢您的输入 - 它可能会在其他时候派上用场:)
    • 我将在今天晚些时候尝试该解决方案! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    相关资源
    最近更新 更多