0

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.

1
  • 3
    resource = string.Join(", ", setOfData.Select(z => z.Resource).Distinct()); Commented Mar 14, 2018 at 6:33

2 Answers 2

5

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; }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This is exactly what I was looking for.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.