比较引用类型列表中的字符串

时间:2015-03-10 11:46:21

标签: c#

我在C#中实现了代码,逐个字符地比较2个字符串,并返回2个字符串之间的百分比差异。以下是代码。

public static double percentage(string a, string b)
    {  
        double percent;

        if (a == b) //Same string, no iteration needed.
            percent = 100;
        if ((a.Length == 0) || (b.Length == 0)) //One is empty, second is not
        {
            percent = 0;
        }
        double maxLen = a.Length > b.Length ? a.Length : b.Length;
        int minLen = a.Length < b.Length ? a.Length : b.Length;
        int sameCharAtIndex = 0;
        for (int i = 0; i < minLen; i++) //Compare char by char
        {
            if (a[i] == b[i])
            {
                sameCharAtIndex++;
            }
        }
        percent = sameCharAtIndex / maxLen * 100;
        Console.WriteLine("Difference {0}", percent.ToString());
        return percent;
      }  

我从我的数据库中的2个表中获取数据,并将数据存储在2个列表中,如下所示

                //ListOfPerson
                while (reader.Read())
                {
                    //var person = new Person();
                    person.ID = Convert.ToInt32(reader["ID"]);
                    person.firstName = reader["FirstName"].ToString();
                    person.middleName = reader["MiddleName"].ToString();
                    person.lastName = reader["LastName"].ToString();

                    ListOfPerson.Add(person);
                    Console.WriteLine("{0} {1} {2} {3}", person.ID, person.firstName, person.middleName, person.lastName);
                } 


                //ListOfEmployee
                while (reader1.Read())
                {
                    //var employee = new Employee();

                    employee.firstName = reader1["FirstName"].ToString();
                    employee.lastName = reader1["LastName"].ToString();

                    ListOfEmployee.Add(employee);

                    Console.WriteLine("{0} {1}", employee.firstName, employee.lastName);
                }

我想逐个字符地比较person.firstName(在整个ListOfPerson中)和employee.firstName(在整个ListOfEmployee中)并获得百分比。 我试过这样做:

               foreach (var p in ListOfPerson)
                {
                    for (int i = 0; i < ListOfEmployee.Count(); i++)
                    {
                        clsCompare.percentage(p.firstName, ListOfEmployee[i].firstName);
                    }
                }

但它只循环遍历ListOfPerson和ListOfEmployee中的姓氏。我怎样才能实现这一目标?循环遍历2个列表中逐个字符比较的所有名称。

1 个答案:

答案 0 :(得分:1)

代码不正确。像这样添加return语句:

if (a == b) //Same string, no iteration needed.
    return percent = 100;
if ((a.Length == 0) || (b.Length == 0)) //One is empty, second is not
{
    return percent = 0;
}

new语句是必需的。您已将其标记为评论。如果没有new语句,则不会为新值分配任何新内存。您将保存同一对象中的所有值,从而覆盖以前的值。

您还需要对返回的值执行某些操作。你只是在调用这个函数。您应该将该值存储在变量中或打印出来。