Reputation: 9
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
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:
SourceValueField
and MappedValuesField
(see Zip method).Source
field matches any of the sourceDestinationValue
values.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