Shaswat Swarup
Shaswat Swarup

Reputation: 9

Filter a string array from string array in an object

I have an array of string: string[] sourceDestinationValue. There's another object: XRefResponse mappedValuesResponse. The properties of the object are mentioned below:

    public string[] SourceValuesField;

    public string[] MappedValuesField;

    public bool AllValuesMappedField;

    public string[] CommentField;

I want to filter SourceValuesField property of XRefResponse class based upon sourceDestinationValue and return an array of MappedValuesField property for matched values using Linq.

I have tried this:

var result = sourceDestinationValue.Where(x => mappedValuesResponse.SourceValues.Any(s => s.Contains(x))).ToArray();

Upvotes: 1

Views: 100

Answers (1)

Rubidium 37
Rubidium 37

Reputation: 711

If I understood correctly, you have a class like this one:

class XRefResponse
{
    public string[] SourceValuesField;
    public string[] MappedValuesField;
    public bool AllValuesMappedField;
    public string[] CommentField;
}

And a variable like this one:

XRefResponse mappedValuesResponse

You want to use Linq (I don't see any EntityFramework specialized code in your sample) to get all values of MappedValuesField whose positions match the values of SourceValuesField that are found in a given array.

Based on that, I assume that SourceValuesField and MappedValuesField are both non-null and have the same length.

Then, a possible solution can be:

string[] Filter(XRefResponse mappedValuesResponse, string[] sourceDestinationValue)
    {
        var allPairs = mappedValuesResponse.SourceValuesField.Zip(mappedValuesResponse.MappedValuesField, (source, mapped) => new { Source = source, Mapped = mapped });
        var matchedPairs = allPairs.Where(pair => Array.IndexOf(sourceDestinationValue, pair.Source) >= 0);
        var result = matchedPairs.Select(pair => pair.Mapped);
        return result.ToArray();
    }

This method does the following things:

  1. Creates a sequence of pairs from values of SourceValueField and MappedValuesField (see Zip method).
  2. Filters all the pairs where the Source field matches any of the sourceDestinationValue values.
  3. Returns a new sequence that contains only the Mapped values from the previous step.

Local variables help understanding the code and separating sub-operations, but you can remove them if you like.

In case SourceValueField and MappedValuesField are always handled in pairs, a better implementation could be having a single array containing values from both fields (maybe using Tuples, e.g.: public Tuple<string,string>[] ValuesField;) or a dictionary where the keys correspond to SourceValueField and the values correspond to MappedValuesField (e.g.: public Dictionary<string,string> ValuesField;).

Upvotes: 1

Related Questions