更新时间:2023-01-24 10:26:58
public List<string> names = new List<string>();
while(reader.Read())
{
string name = reader["FirstName"].ToString().ToUpper());
if (!names.Contains(name))
names.Add(names);
else
{
// handle reporting the duplicate here
}
}
如果列表很大,那么考虑使用Dictionary或HashSet而不是List来提高性能。
如果你只需要一个列表那些没有重复的名字
If the list is large, then consider using a Dictionary or a HashSet instead of a List to improve performance.
If all you need is a list of the names with no duplicates then
public List<string> names = new List<string>();
while(reader.Read())
{
string name = reader["FirstName"].ToString().ToUpper());
names.Add(names);
names = names.Distinct().ToList();
}
这个或类似的东西应该适合:
This or something similar should suit:
public List<string> names = new List<string>();
while (reader.Read())
{
string name = reader["FirstName"].ToString().ToUpper());
if (names.Count == 0)
{
names.Add(name);
}
else
{
bool duplicate;
foreach (string n in names)
{
if (n == name)
duplicate = true;
}
if (!duplicate)
names.Add(name);
}
}
如果列表为空,那么你总是添加字符串,然后每次你如果列表中不存在,则只读取您添加的名称。这样你就永远不会产生一个带有重复的列表。
如果这不是你想要的那么我恐怕我误解了你的要求。
祝你好运。 :)
Here you are always adding the string if the list is empty, then each time you read a name you are only adding it if it does not exist in the list. This way you will never produce a list with duplicates in it.
If this is not what you want then I'm afraid I have misunderstood your request.
Good luck. :)
根据您的评论,这是一个更新的解决方案:
在命名空间中创建一个类型,类似于:
Based on your comment, here is an updated solution:
Create a type in your namespace, similar to this:
struct Record
{
public string Name;
public string PhoneNumber;
}
然后在你的方法中,比较类型值:
Then in your method, compare the type values:
public List<Record> Records = new List<Record>();
while (reader.Read())
{
string name = reader["FirstName"].ToString().ToUpper());
string phoneNumber = reader["PhoneNumber"].ToString();
Record r = new Record();
if (names.Count == 0)
{
r.Name = name;
r.PhoneNumber = phoneNumber;
Records.Add(r);
}
else
{
bool duplicate;
foreach (Record record in Records)
{
if (record.Name == name &&
record.PhoneNumber == phoneNumber)
duplicate = true;
}
if (!duplicate)
Records.Add(r);
else
{
// Use whatever means you see fit here to
// ask the user if they wish to replce the
// existing record
}
}
}