温馨提示×

C#怎么将Intersect查询结果转换为不同的数据类型

c#
小亿
83
2024-04-01 21:36:00
栏目: 编程语言

在C#中,可以使用LINQ语句将Intersect查询结果转换为不同的数据类型。以下是一个示例:

假设有两个集合a和b,我们想要找出两个集合中相同的元素,并将结果转换为另一种数据类型。可以按照以下步骤进行操作:

using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> a = new List<int> { 1, 2, 3, 4, 5 };
        List<int> b = new List<int> { 3, 4, 5, 6, 7 };
        
        var intersectResult = a.Intersect(b).Select(x => new { Number = x });

        foreach (var item in intersectResult)
        {
            Console.WriteLine(item.Number);
        }
    }
}

在这个示例中,我们首先使用Intersect方法找出两个集合中相同的元素,然后使用Select方法将结果转换为一个匿名类型,该匿名类型包含一个Number属性。最后,我们遍历结果并输出Number属性的值。

通过这种方法,我们可以将Intersect查询结果转换为不同的数据类型,以满足具体的需求。

0