0

I have seen other people having a similar problem, but no solution has been able help me with mine.

I was looking for a way to make:

List<int> Factors = new List<int> {2, 5, 5, 7, 2, 3};

return:

{7, 3};

Is there any way that this can be done?

3
  • 1
    How is that removing duplicate values? what happened to 2, 5? Commented Nov 16, 2014 at 17:29
  • You may want to see the answer to this question: stackoverflow.com/questions/47752/… Commented Nov 16, 2014 at 17:29
  • @VikasGupta, OP want's only those number which have only one appearance. Commented Nov 16, 2014 at 17:32

2 Answers 2

9

Using GroupBy you can group the numbers and get those groups that has only one number:

Factors = Factors.GroupBy(x => x)
   .Where(g => g.Count() == 1)
   .Select(g => g.Key)
   .ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

@Selamn22 - I don't think there's any need to filter. Factors.GroupBy(x => x).Select(x => x.Key).ToList(); will do.
@RahulSingh that won't remove the duplicates. it will do exact same thing with Distinct.
@Selman22 - Oops Yes Got It! Misunderstood the question. +1 :-)
0

Probably a Non LINQ solution. Add the numbers in list as key to the hashtable. in next iteration if the same key found in hashtable then increase it's corresponding value. so, at end you will remain with only those numbers which have only one appearance.

    static void Main(string[] args)
    {
        List<int> Factors = new List<int> { 2, 5, 5, 7, 2, 3, 2, 9, 8, 9, 11, 9, 12, 9, 13, 9 };
        Hashtable ht = new Hashtable();
        foreach (var item in Factors)
        {
            if (ht.ContainsKey(item))
            {
                ht[item] = Convert.ToInt32(ht[item]) + 1;
            }
            else
                ht.Add(item, 1);
        }

        foreach (var item in ht.Keys)
        {
            if (Convert.ToInt32(ht[item]) == 1)
            Console.WriteLine(item.ToString());
        }
    }

2 Comments

This code only removes elements which occur an even number of times. It will leave elements which occur 1, 3, 5 etc times.
@fejesjoco, what about now but thanks for pointing that. didn't think of that use case.

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.