luckyluke
luckyluke

Reputation: 167

C# Compare two Lists

Background: I have two lists that hold strings. List a and List b. At the moment I write the values of List a in an excel spreadsheet to column A, and the values of List b into Column. List b should have the same data as List a and be in sequence. This is not always the case.

Problem: When I write values of List b in excel, I want to write the value in the cell if it is in list a at the same point, if not I want to write an empty string into the cell.

Edit: Thanks for replies and answers work very well, just realised that what I really need is :

If two lists are:

a = {"a", "b", "c", "d", "e" }
b = {"a", "d", "e" }

the result of the operation should be:

{ "a", "", "", "d", "e" }

Upvotes: 2

Views: 597

Answers (3)

sloth
sloth

Reputation: 101142

One way is to zip your lists together and replace the "wrong" value in list b with an empty string:

var a = new [] {"a",   "b", "c",   "d"};
var b = new [] {"a", "Foo", "c", "Bar"};

var fixed_b = a.Zip(b, (x, y) => x == y ? x : "");

fixed_b now yields "a", "", "c" and "".

When writing your data to your excel spreadsheet, simply iterate over fixed_b instead of b

Edit:

According to your comments:

You could create a little helper method like this:

IEnumerable<T> FillBlanks<T>(IEnumerable<T> source, IEnumerable<T> collection, T blank)
{
    using(var e = collection.GetEnumerator())
    {
        bool more = e.MoveNext();
        foreach(var x in source)
            if(more && x.Equals((T)e.Current))
            {
                yield return x;
                more = e.MoveNext();
            }
            else
                yield return blank;
    }
}

var fixed_b = FillBlanks(a, b, String.Empty);

Upvotes: 5

Alex Filipovici
Alex Filipovici

Reputation: 32571

Try this:

class Program
{
    static void Main(string[] args)
    {
        List<string> listA = new List<string>() { "a", "b", "c" };
        List<string> listB = new List<string>() { "a", "c", "b" };

        var result = listB.Select((b, index) =>
            (index == listA.IndexOf(b)) ? b : "");
    }
}

Upvotes: 0

Moo-Juice
Moo-Juice

Reputation: 38820

int max = aList.Count > bList.Count ? aList.Count : bList.Count;
for(int i = 0; i < max; ++i)
{
    if(i < aList.Count)
        Write(aList[i]);

    if(i < bList.Count)
    {
        if(i < aList.Count)
            Write(aList[i] == bList[i] ? bList[i] : "");
        else
            Write(bList[i]);
    }
}

This assumes Write actually writes data to the spreadsheet.

Upvotes: 1

Related Questions