从对象中的字符串数组中过滤字符串数组

时间:2020-04-15 11:02:52

标签: c# .net linq

我有一个字符串数组:string[] sourceDestinationValue。还有另一个对象:XRefResponse mappedValuesResponse。该对象的属性如下:

    public string[] SourceValuesField;

    public string[] MappedValuesField;

    public bool AllValuesMappedField;

    public string[] CommentField;

我想根据sourceDestinationValue筛选XRefResponse类的SourceValuesField属性 并使用Linq返回一个用于匹配值的MappedValuesField属性数组。

我已经尝试过了:

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

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么您会遇到一个像这样的课程:

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

还有一个像这样的变量:

XRefResponse mappedValuesResponse

您想使用Linq(您的示例中没有看到任何EntityFramework专用代码)来获取MappedValuesField的所有值,其位置与给定数组中找到的SourceValuesField的值相匹配。

基于此,我假设SourceValuesFieldMappedValuesField都不为空,并且长度相同。

然后,可能的解决方案可以是:

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();
    }

此方法执行以下操作:

  1. 根据SourceValueFieldMappedValuesField的值创建成对的序列(请参见Zip方法)。
  2. 过滤所有Source字段与任何sourceDestinationValue值匹配的对。
  3. 返回一个新序列,该序列仅包含上一步中的Mapped个值。

局部变量有助于理解代码并分隔子操作,但是您可以根据需要将其删除。

如果SourceValueFieldMappedValuesField总是成对处理,则更好的实现可能是使用包含两个字段中的值的单个数组(可能使用Tuples,例如:public Tuple<string,string>[] ValuesField;)或字典,其中键对应于SourceValueField,而值对应于MappedValuesField(例如:public Dictionary<string,string> ValuesField;)。