检查源列表中是否存在多个子列表



我定义了两个类:

public class MyclassSource
{
public string Name { get; set; }
public string Value { get; set; }
public MyclassSource(string x, string y)
{
Name = x;
Value = y;
}
}
public class MyclassTarget
{
public string Name { get; set; }
public string Value { get; set; }
}

我已经创建了一个MyclassSource列表,如下所示

List<MyclassSource> SourceList = new List<MyclassSource>
{
new MyclassSource("T1","V1"),
new MyclassSource("T3","V3"),
new MyclassSource("T4","V4"),
new MyclassSource("T7","V7"),
new MyclassSource("T8","V8"),
};

一个字典,我们称之为Mapper,声明为:

List<string> s1 = new List<string> {"T1", "T5"};
List<string> s2 = new List<string> {"T4", "T6"};
List<string> s3 = new List<string> {"T3", "T2"};
List<string> s4 = new List<string> { "T4", "T7" };
Dictionary<string, List<string>> Mapper = new Dictionary<string, List<string>>
{
{"X1", s1}, {"X2", s2}, {"X3", s3}, {"X4", s4}
};

对于字典映射器中的每个键,即x1, x2, x3, x4,有可能的列表字符串值:对于X1,值列表为s1,因此可能的值为T1, T5等

这些值可以出现在Sourcelist中。我们需要确定源列表中是否存在字典中每个键的可能字符串值,如果存在,则获取相应的值。只有在找到单个匹配时,才应该进行取取,如果T4, T7这两个值都在源列表中,则抛出异常。

我已经尝试了一些代码,但无法按预期获取。其次,我在想是否有可能避免两个for循环

foreach (var item in Mapper)
{
MyclassTarget t = new MyclassTarget {Name = item.Key};               

foreach (var value in item.Value)
{
if (SourceList.Select(x => x.Name).Contains(value))
{
t.Value =  // assing the value somehow if unique match found.
}
}
}

预期结果将是当我们在上面的for循环中迭代时,MyClassTarget对象被分配如下值

Name        value
obj1    X1           V1
obj2    X2           V4
Obj3    X3           V3
Obj4    Exceptions as more than one value matches  

怎么样:

foreach (var item in Mapper)
{
MyclassTarget t = new MyclassTarget { Name = item.Key };
t.Value = SourceList.Where(x => item.Value.Contains(x.Name)).Count() == 1 ? SourceList.First(y => item.Value.Contains(y.Name)).Value : "Exception";
}

这会产生期望的结果吗?

相关内容

  • 没有找到相关文章

最新更新