Nisha
Nisha

Reputation: 1439

Getting comma separated distinct values from columns in C#

I have a stored procedure that returns the below sample result set. This is what I get in my code.

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

I would like to manipulate the result set to get the below result preferably in 3 different variables.

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

We are required to use LINQ to get this. Any help would be appreciated.

Upvotes: 0

Views: 191

Answers (2)

Abhilash Ravindran C K
Abhilash Ravindran C K

Reputation: 1856

Following code will be helpful to you,

 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());

Upvotes: 1

PSK
PSK

Reputation: 17943

You can try like following.

   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());

Complete Example:

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

Upvotes: 5

Related Questions