0

Novice linq user but prim_clus_list &ref_clus_list are a List and ref_clus & prim_clus are strings. I'm trying to do the following but it's not working.

string[] clus_list = prim_clus_list.Union(ref_clus_list).Union(ref_clus.ToList()).Union(prim_clus.ToList()).ToArray<string>();

How can I do this in one line? I want them all in one list with no duplicates.

CS1928: 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.Queryable.Union(System.Linq.IQueryable, System.Collections.Generic.IEnumerable)' has some invalid arguments

Also this alone works fine:

string[] clus_list = prim_clus_list.Union(ref_clus_list).ToArray<string>();
5
  • If ref_clus is string, then ref_clus.ToList().ToList() shouldn't compile, unless you have extension methods for string Commented May 30, 2018 at 1:05
  • Yep, sorry, left out the error. Updated. Commented May 30, 2018 at 1:05
  • If you are novice then you should read documentation of linq, union and string first Commented May 30, 2018 at 1:05
  • Use Linq aggregate Commented May 30, 2018 at 1:06
  • 1
    @ChetanRanpariya - if we read documentation carefully, we don't need StackOverflow then :) Commented May 30, 2018 at 1:07

2 Answers 2

2

Use .Append method to append single item to IEnumerable

var result = prim_clus_list.Append(ref_clus)
                           .Append(prim_clus)
                           .Union(ref_clus_list)
                           .ToArray();

Put Union in the end of the chain to get rid of duplicates.

Enumerable.Append(IEnumerable, TSource) Method

Sign up to request clarification or add additional context in comments.

2 Comments

I get an CS0023 Operator '.' cannot be applied to operand of type 'void' error when I try this code?
My bad. I had a rogue extension method that was taking precedence.
0

This is what you need:

var prim_clus_list = new List<string>() { "A", "B" };
var ref_clus_list = new List<string>() { "C", "D" };
var ref_clus = "E";
var prim_clus = "F";

string[] clus_list =
    prim_clus_list
        .Union(ref_clus_list)
        .Union(new [] { ref_clus })
        .Union(new [] { prim_clus })
        .ToArray<string>();

That gives:

A 
B 
C 
D 
E 
F 

Basically ref_clus.ToList() returns a List<char>, but new [] { ref_clus } returns an IEnumerable<string> which can be used with .Union.

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.