Addition of two lists?

says i have a list of strings:

A, B, C, D

Then the following list of lines

B, C, D

I want to know which items are in the first list, which are not in the second list, so the result will be A

I do not know what the extension method is called. I know that I can use concat, union, intersect for similar list comparisons, but I just don’t know the name for this particular task.

Adding, I'm interested in duplicates, so if the first list is:

A, A, A, B, C, D

and the second list

B, C, D

I want to receive

A, A, A

Thank!

+5
source share
4 answers

, , :

var result = list1.Except(list2);
+14

"" BCL , .

, , , . - :

// yield all members of "sequence" omitting those in "except"
static IEnumerable<string> Filter(
    this IEnumerable<string> sequence, 
    IEnumerable<string> except)
{
    var set = new HashSet<string>(except); // Burn memory to save time
    return from item in sequence 
           where !set.Contains(item) 
           select item;
}

, .

var sequence = new List<string>() { A, B, A, C, D };
var except = new List<string>() { B, C };
var result = sequence.Filter(except).ToList();
+4
var result = list1.Where(i => !list2.Contains(i));
+3

, , , : . - , .

BagDifference, , .

public class Bag<T> : Dictionary<T, int>
{
    public Bag(IEnumerable<T> sequence)
    {
        foreach (var item in sequence)
        {
            if (!ContainsKey(item)) this[item] = 0;
            ++this[item];
        }
    }
}

public static class EnumerableExtensions
{
    public static IEnumerable<T> BagDifference<T>(this IEnumerable<T> sequence1, IEnumerable<T> sequence2)
    {
        var bag1 = new Bag<T>(sequence1);
        var bag2 = new Bag<T>(sequence2);
        foreach (var item in bag1.Keys)
        {
            var count1 = bag1[item];
            var count2 = bag2.ContainsKey(item) ? bag2[item] : 0;
            var difference = Math.Max(0, count1 - count2);
            for (int i = 0; i < difference; i++)
                yield return item;
        }
    }
}

class Program
{

    static void Main(string[] args)
    {
        var sequence = new List<string>() { "A", "B", "A", "C", "D" };
        var except = new List<string>() { "A", "B", "C", "C" };
        var difference = sequence.BagDifference(except).ToList();
    }
}
0
source

All Articles