简体   繁体   English

C#比较两个列表

[英]C# Compare two Lists

Background: I have two lists that hold strings. 背景:我有两个包含字符串的列表。 List a and List b. 列出a和列表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. 目前,我将Excel电子表格中的List a的值写入A列,并将List b的值写入Column中。 List b should have the same data as List a and be in sequence. 列表b应具有与列表a相同的数据,并应按顺序排列。 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. 问题:当我在excel中写入列表b的值时,如果要同时在列表a中将值写入单元格中,那么我想在单元格中写入该值;否则,我想向该单元格中写入一个空字符串。

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" }

One way is to zip your lists together and replace the "wrong" value in list b with an empty string: 一种方法是将列表zip在一起,然后用空字符串替换列表b中的“错误”值:

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 "" . fixed_b现在产生"a""""c"""

When writing your data to your excel spreadsheet, simply iterate over fixed_b instead of b 将数据写入excel电子表格时,只需遍历fixed_b而不是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);
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. 假设Write实际上将数据写入电子表格。

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 : "");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM