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?

GriffinMite
  • 193
  • 1
  • 3
  • 9

2 Answers2

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();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
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());
        }
    }
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • 1
    This code only removes elements which occur an even number of times. It will leave elements which occur 1, 3, 5 etc times. – fejesjoco Nov 16 '14 at 17:52
  • @fejesjoco, what about now but thanks for pointing that. didn't think of that use case. – Rahul Nov 16 '14 at 18:03