MST

星途 面试题库

面试题:C#模式匹配与switch表达式在泛型及递归场景下的优化应用

设计一个泛型方法,使用C#的模式匹配和switch表达式来处理嵌套的泛型集合(例如List<List<int>>或List<List<List<string>>>这种多层次的泛型集合)。要求该方法能够递归地遍历嵌套集合,并根据元素类型进行不同的操作:对于整数类型元素求总和,对于字符串类型元素拼接成一个长字符串。请尽可能优化代码性能,考虑到集合可能非常大的情况。
44.1万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
using System;
using System.Collections.Generic;

public static class CollectionProcessor
{
    public static object ProcessNestedCollection<T>(IEnumerable<T> collection)
    {
        return collection switch
        {
            IEnumerable<IEnumerable<int>> intCollections => SumNestedIntCollections(intCollections),
            IEnumerable<IEnumerable<string>> stringCollections => ConcatNestedStringCollections(stringCollections),
            _ => throw new NotSupportedException("Unsupported collection type")
        };
    }

    private static int SumNestedIntCollections(IEnumerable<IEnumerable<int>> collections)
    {
        int sum = 0;
        foreach (var subCollection in collections)
        {
            foreach (var num in subCollection)
            {
                sum += num;
            }
        }
        return sum;
    }

    private static string ConcatNestedStringCollections(IEnumerable<IEnumerable<string>> collections)
    {
        var stringBuilder = new System.Text.StringBuilder();
        foreach (var subCollection in collections)
        {
            foreach (var str in subCollection)
            {
                stringBuilder.Append(str);
            }
        }
        return stringBuilder.ToString();
    }
}

你可以使用以下方式调用这个方法:

class Program
{
    static void Main()
    {
        var intList = new List<List<int>>
        {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 5, 6 }
        };
        var sum = (int)CollectionProcessor.ProcessNestedCollection(intList);
        Console.WriteLine($"Sum of integers: {sum}");

        var stringList = new List<List<string>>
        {
            new List<string> { "Hello, ", "world! " },
            new List<string> { "How ", "are ", "you?" }
        };
        var concatenated = (string)CollectionProcessor.ProcessNestedCollection(stringList);
        Console.WriteLine($"Concatenated string: {concatenated}");
    }
}

代码说明

  1. ProcessNestedCollection方法:这是一个泛型方法,接受一个IEnumerable<T>类型的参数。通过switch表达式对传入的集合进行模式匹配,如果是IEnumerable<IEnumerable<int>>类型,则调用SumNestedIntCollections方法;如果是IEnumerable<IEnumerable<string>>类型,则调用ConcatNestedStringCollections方法;否则抛出NotSupportedException
  2. SumNestedIntCollections方法:遍历嵌套的整数集合,对所有整数求和。
  3. ConcatNestedStringCollections方法:使用StringBuilder来高效地拼接嵌套的字符串集合,以优化性能,适合处理大集合。
  4. 调用示例:在Main方法中,分别创建了嵌套的整数集合和字符串集合,并调用ProcessNestedCollection方法进行处理和输出结果。