繁体   English   中英

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

[英]Check if multiple sub lists are present in a source list

我有两个类定义为:

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

对于字典 Mapper 中的每个键,即 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.
                    }
                }
        }
  

预期结果将是 MyClassTarget object 在我们遍历上面的 for 循环时被分配以下值

        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";
}

这会产生预期的结果吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM