Question

As a follow up to my last question here: Filtering a list of HtmlElements based on a list of partial ids

I need to take this statement:

doc.All.Cast<HtmlElement>()
    .Where(x => x.Id != null)
    .Where(x => ids
        .Any(id => x.Id.Contains(id))).ToList();

and join it with an array of strings called fields. Assuming the array and list will have the same amount of elements each and line up correctly. I tried using Zip() but thought I might need to use an additional linq statement to make it work.

Was it helpful?

Solution

Assuming that fieldList[0] and IdList[0] corresponding to each other, you can do the following:

var IdList = doc.All.Cast<HtmlElement>()
            .Where(x => x.Id != null)
            .Where(x => ids
            .Any(id => x.Id.Contains(id))).ToList();

var resultList = fieldList 
             .Select( (item, index) => new { Field = item, Id = IdList[index] })
             .ToDictionary(x => x.Id, x => x.Field);

OTHER TIPS

You have mentioned it already, you can use Enumerable.Join:

var joined = from id in fields
             join ele in elements on id equals ele.Id
             select new { Element = ele, ID = id };
var dict = joined.ToDictionary(x => x.ID, x => x.Element);

I've presumed that you want to join them via ID. I've also presumed that the string[] contains only unique ID's. Otherwise you need to use Distinct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top