使用SelectMany

时间:2016-02-02 04:38:18

标签: c# linq

在下面的代码中,我们可以显示SelectSelectMany运算符之间的差异。

有没有办法避免常用技巧?例如,如果两名员工拥有C#技能,那么我只想打印一次。

namespace LinqOperators
{
    class Employee
    {
        public string Name { get; set; }
        public List<string> Skills { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> employees = new List<Employee>();
            Employee emp1 = new Employee { Name = "Deepak", Skills = new List<string> { "C", "C++", "Java" } };//Adding Skills List to Employee List i.e List of List
            Employee emp2 = new Employee { Name = "Karan", Skills = new List<string> { "SQL Server", "C#", "ASP.NET" } };

            Employee emp3 = new Employee { Name = "Lalit", Skills = new List<string> { "C#", "ASP.NET MVC", "Windows Azure", "SQL Server" } };

            employees.Add(emp1);
            employees.Add(emp2);
            employees.Add(emp3);

            // Query using Select()
            IEnumerable<List<String>> resultSelect = employees.Select(e => e.Skills);

            Console.WriteLine("**************** Select ******************");

            // Two foreach loops are required to iterate through the results
            // because the query returns a collection of arrays.
            foreach (List<String> skillList in resultSelect)
            {
                foreach (string skill in skillList)
                {
                    Console.WriteLine(skill);
                }
                Console.WriteLine();//To differntiate Two Skill Lists
            }

            // Query using SelectMany()
            IEnumerable<string> resultSelectMany = employees.SelectMany(emp => emp.Skills);

            Console.WriteLine("**************** SelectMany ******************");

            // Only one foreach loop is required to iterate through the results 
            // since query returns a one-dimensional collection.
            foreach (string skill in resultSelectMany)
            {
                Console.WriteLine(skill);
            }

            Console.ReadKey();
        }
    }

} 

2 个答案:

答案 0 :(得分:4)

SelectMany会压扁您的IEnumerable,使其不会产生IEnumerable of IEnumerablesIEnumerable

IEnumerable<IEnumerable<string>> skills; //not this [[C#, Java], [C, C++, Java, C#]]
IEnumerable<string> skills; //but this [C#, Java, C, C++, Java, C#]

您可以在Distinct中使用resultSelectMany仅获得一次普通技能。

resultSelectMany = resultSelectMany.Distinct(); //[C#, Java, C, C++]

或者把它放在同一行:

// Query using SelectMany()
IEnumerable<string> resultSelectMany = employees.SelectMany(emp => emp.Skills).Distinct();

答案 1 :(得分:1)

您可以使用additional encoders删除重复项