将逗号分隔的不同值与C#中的列分开

时间:2018-03-14 06:32:06

标签: c# sql-server

我有一个存储过程,它返回下面的示例结果集。这就是我在代码中得到的内容。

Resource  |  ResourceGroup  |  ResourceType
----------|-----------------|----------------
 R1       |    RG1          |    RT1
 R1       |    RG2          |    RT1
 R2       |    RG2          |    RT2
 R3       |    RG3          |    RT2
 R4       |    RG1          |    RT2
----------|-----------------|---------------

我想操纵结果集以获得以下结果,最好是3个不同的变量。

String resource = "R1, R2, R3, R4"  // Distinct values in Resource column
String resourceGroup = "RG1, RG2, RG3" // Distinct values in ResourceGroup column
String resourceType = "RT1, RT2" // Distinct values in ResourceType column

我们需要使用LINQ才能获得此功能。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:5)

您可以尝试以下内容。

   String resource = String.Join(",", resources.Select(x => x.Resource).Distinct());
   String resourceGroup = String.Join(",", resources.Select(x => x.ResourceGroup).Distinct());
   String resourceType = String.Join(",", resources.Select(x => x.ResourceType).Distinct());

完整示例:

class Program
    {
        static void Main(string[] args)
        {
            List<Resources> resources = new List<Resources>();
            resources.Add(new Resources { Resource = "R1", ResourceGroup = "RG1", ResourceType = "RT1" });
            resources.Add(new Resources { Resource = "R2", ResourceGroup = "RG1", ResourceType = "RT1" });
            resources.Add(new Resources { Resource = "R3", ResourceGroup = "RG3", ResourceType = "RT2" });
            String resource = String.Join(",", resources.Select(x => x.Resource).Distinct());
        }
    }

    class Resources
    {
        public string Resource { get; set; }
        public string ResourceGroup { get; set; }
        public string ResourceType { get; set; }
    }

答案 1 :(得分:1)

以下代码对您有所帮助,

 String resource = string.Join(",", your_context_table.Select(x => x.Resource).Distinct());
 String resourceGroup  = string.Join(",", your_context_table.Select(x => x.ResourceGroup).Distinct());
 String resourceType= string.Join(",", your_context_table.Select(x => x.ResourceType).Distinct());