繁体   English   中英

如何比较两个字符串列表列表

[英]How to compare two lists of lists of strings

我正在尝试将 2 个集合与字符串列表进行比较。 第一个 object 与字符串列表:

a0, b0, c0

a1, b1, c0

a1, b2, c0

a1, b2, c1

第二

a0, b0, c0

a1, b2, c0

我有方法 go 从 object 获取字符串列表

public List<string> GetPlainRow(int index)
{
    if(index >= _countRows || index < 0)
    {
        throw new IndexOutOfRangeException();
    }

    List<string> returnedRow = new List<string>();

    foreach (KeyValuePair<string, List<string>> entry in _dataRows)
    {
        returnedRow.Add(entry.Value[index]);
    }
    return returnedRow;
}

试图将对象列表与:

for (int i = 0; i < dataCollection.CountRows; i++)
{
    var newRow = table.NewRow();
    for (var j = 0; j < dataCollection.GetPlainRow(i).Count; j++)
    {
        newRow[j] = dataCollection.GetPlainRow(i)[j];

    }
    for (int k = 0; k < dataCollection.CountRows; k++)
    {
        for (int l = 0; l < dataRestrained.CountRows; l++)
        {
           if(dataCollection.GetPlainRow(k).SequenceEqual(dataRestrained.GetPlainRow(l)))
            {
                found = true;
            }
        }
    }
    newRow[dataCollection.CountRows - 2] = found;
    found = false;
    table.Rows.Add(newRow);
}

但似乎每次它都返回 true,但是当我使用 Equals 而不是 SequenceEqual 时,它返回 false。

为了简单起见,我为结果添加了 class:

   internal class Result
            {
                public List<string> List { get; set; }
                public bool IsExisted { get; set; }
            }

然后我做了一个 EqualityComparer....

  internal class ListOfStringEqualityComparer : IEqualityComparer<List<string>>
        {
            public bool Equals(List<string> b1, List<string> b2)
            {
                if (b1.Count != b2.Count) return false;
                for (int i = 0; i < b1.Count; i++)
                {
                    if (b1[i] != b2[i]) return false;
                }
                return true;
            }

            public int GetHashCode(List<string> b2)
            {
                int hCode = 0;
                for (int i = 0; i < b2.Count; i++)
                {
                    hCode = EqualityComparer<string>.Default.GetHashCode(b2[i]);
                }
                return hCode.GetHashCode();
            }
        }

现在你可以试试这个:

 ListOfStringEqualityComparer  listOfStringEqualityComparer= new ListOfStringEqualityComparer();
        var q = (from c in bigList
                 select new Result() { List = new List<string>(c), IsExisted = smallList.Contains(c, listOfStringEqualityComparer) });

如果有帮助,现在让我...

也许是这样的

class Someclass
{
  string data;
  bool found;
}

Someclass data = A.Select(c => new Someclass(){data = c, found = B.Contains(c)});

暂无
暂无

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

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