Comparing two string arrays in C#

前端 未结 5 640
暖寄归人
暖寄归人 2021-01-07 16:18

Say we have 5 string arrays as such:

string[] a = {\"The\",\"Big\", \"Ant\"};
string[] b = {\"Big\",\"Ant\",\"Ran\"};
string[] c = {\"The\",\"Big\",\"Ant\"};         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-07 16:39

    If you want to compare them all in one go:

    string[] a = { "The", "Big", "Ant" };
    string[] b = { "Big", "Ant", "Ran" };
    string[] c = { "The", "Big", "Ant" };
    string[] d = { "No", "Ants", "Here" };
    string[] e = { "The", "Big", "Ant", "Ran", "Too", "Far" };
    
    // Add the strings to an IEnumerable (just used List here)
    var strings = new List { a, b, c, d, e };
    
    // Find all string arrays which match the sequence in a list of string arrays
    // that doesn't contain the original string array (by ref)
    var eq = strings.Where(toCheck => 
                                strings.Where(x => x != toCheck)
                                .Any(y => y.SequenceEqual(toCheck))
                          );
    

    Returns both matches (you could probably expand this to exclude items which already matched I suppose)

提交回复
热议问题