Mötz
Mötz

Reputation: 1722

Linq to objects - Search collection with value from other collection

I've tried to search SO for solutions and questions that could be similar to my case.

I got 2 collections of objects:

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

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

I fill the list from my datalayer:

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

I now want to find that one object in colBRSDocuments where x.IdentifierValue is equal to the one object in colBRSMetadata y.Value. I just need to find the BRSDocument that matches a value from the BRSMetadata objects.

I used a ordinary foreach loop and a simple linq search to find the data and break when the value is found. I'm wondering if the search can be done completely with linq?

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

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

Hope that some of you guys can push me in the right direction...

Upvotes: 2

Views: 845

Answers (2)

gilles emmanuel
gilles emmanuel

Reputation: 221

Use Linq ? Something like this should do the job :

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

If you are just interested by the first item, then the code would be :

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

Upvotes: 0

dav_i
dav_i

Reputation: 28107

Why not do a join?

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

If there's only meant to be one then you can do:

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

If you want to return both objects, then you can do the following:

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

then you can access like:

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

Upvotes: 2

Related Questions