使用 StreamReader 计算重复项?

发布于 2024-12-14 13:26:33 字数 231 浏览 2 评论 0原文

我现在使用 StreamReader 来读取人名文件,它是一个文本文件,包含人名,所以显然有重复项,我希望能够显示现在有多少人有相同的人名,例如:

josh
alex
josh
john
alex

我想说,

josh 2
alex 2
john 1

但我似乎找不到一种简单的方法来做到这一点,最简单的方法是什么,

I'm using streamreader now to read a file of people names, it is a text file, of people first names, so there are obviously duplicates, and i want to be able to display how many people have the same now so for example:

josh
alex
josh
john
alex

I want it to say,

josh 2
alex 2
john 1

but I can't seem to find an easy way of doing this, what would be the easiest way about doing this,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

天赋异禀 2024-12-21 13:26:33

我会说使用 Dictionary

Dictionary<string, int> firstNames = new Dictionary<string, int>();

foreach (string name in YourListWithNames)
{
   if (!firstNames.ContainsKey(name))
      firstNames.Add(name, 1);
   else
      firstNames[name] += 1; 
}

当然,解决方案有很多不同的路径,但这就是我解决这个问题的方法。我还没有运行这段代码,但我认为这会对你有所帮助。

I'd say use a Dictionary<string, int>.

Dictionary<string, int> firstNames = new Dictionary<string, int>();

foreach (string name in YourListWithNames)
{
   if (!firstNames.ContainsKey(name))
      firstNames.Add(name, 1);
   else
      firstNames[name] += 1; 
}

Of course there are many different paths to a solution, but this is how I would tackle it. I haven't run this code yet, but this will help you I think.

凉栀 2024-12-21 13:26:33

使用 LINQ 尝试一下。

首先使用以下代码将文本文件读取到 List

const string f = "TextFile1.txt";

// 1
// Declare new List.
List<string> lines = new List<string>();

// 2
// Use using StreamReader for disposing.
using (StreamReader r = new StreamReader(f))
{
    // 3
    // Use while != null pattern for loop
    string line;
    while ((line = r.ReadLine()) != null)
    {
    // 4
    // Insert logic here.
    // ...
    // "line" is a line in the file. Add it to our List.
    lines.Add(line);
    }
}

您需要定义一个类,其中包含名称和相应的计数:

class PersonCount
{
    public string Name { get; set; }
    public int Count { get; set; }
}

最后使用此 Lambda表达式以获得所需的List

List<PersonCount> personCounts = lines.GroupBy(p => p).Select(g => new PersonCount() {Name = g.Key, Count = g.Count()}).ToList();

现在迭代列表以获取名称和重复项的计数。

Try this with LINQ.

First read your text file to a List<string> using this code:

const string f = "TextFile1.txt";

// 1
// Declare new List.
List<string> lines = new List<string>();

// 2
// Use using StreamReader for disposing.
using (StreamReader r = new StreamReader(f))
{
    // 3
    // Use while != null pattern for loop
    string line;
    while ((line = r.ReadLine()) != null)
    {
    // 4
    // Insert logic here.
    // ...
    // "line" is a line in the file. Add it to our List.
    lines.Add(line);
    }
}

You need to define a class where you will have name and accordingly the count:

class PersonCount
{
    public string Name { get; set; }
    public int Count { get; set; }
}

And finally use this Lambda expression to get desired List<string>

List<PersonCount> personCounts = lines.GroupBy(p => p).Select(g => new PersonCount() {Name = g.Key, Count = g.Count()}).ToList();

Now iterate through the list to get the names and the count of duplicates.

西瑶 2024-12-21 13:26:33

使用 HashMap 可以解决您的问题。
当您读取名称时,检查该密钥是否已经存在,如果存在,则更新它(+1),如果不存在,则将其添加到哈希映射中。

最后,您所需要做的就是打印键值对。

Using an HashMap is a solution to your problem.
When you read a name, check if the key is already present, if so, update it (+1), if not add it to your Hash Map.

In the end, all you need to do is print the key-value pairs.

迷离° 2024-12-21 13:26:33

将所有名称存储在 Dictionary中名称

对每一行使用类似的内容:(

var theName = reader.ReadLine();
names[theName] += 1;

如果该项目不存在,则应将计数设置为一)

Store all names in a Dictionary<string, int> names.

Use something like this for each row:

var theName = reader.ReadLine();
names[theName] += 1;

(it should set the count to one if the item do not exist)

内心激荡 2024-12-21 13:26:33
foreach (var keyvalue in File.ReadAllLines(@"C:\....").GroupBy(x => x).Select(x => new { name = x.Key, count = x.Count() }))
{
        Console.WriteLine(keyvalue.name + ": " + keyvalue.count);
}
foreach (var keyvalue in File.ReadAllLines(@"C:\....").GroupBy(x => x).Select(x => new { name = x.Key, count = x.Count() }))
{
        Console.WriteLine(keyvalue.name + ": " + keyvalue.count);
}
柠檬 2024-12-21 13:26:33

当然,您也可以使用 Linq 执行类似的操作(省略错误检查):

var names = new List<string>(
    File.ReadAllText(pathToFile).Split(
    Environment.NewLine.ToCharArray(),
    StringSplitOptions.RemoveEmptyEntries
));
var namesAndOccurrences =
    from name in names.Distinct()
    select name + " " + names.Count(n => n == name);

foreach (var name in namesAndOccurrences)
    Console.WriteLine(name);

根据文件的大小,这可能需要摆脱流;但是,这并不是说如果文件对于内存而言相当大,则应该使用 ReadLine

You could of course also do something like this (error checking omitted), using Linq:

var names = new List<string>(
    File.ReadAllText(pathToFile).Split(
    Environment.NewLine.ToCharArray(),
    StringSplitOptions.RemoveEmptyEntries
));
var namesAndOccurrences =
    from name in names.Distinct()
    select name + " " + names.Count(n => n == name);

foreach (var name in namesAndOccurrences)
    Console.WriteLine(name);

Depending on the size of the file, this might be desirable to get rid of the stream; however, this isn't to say that if the file was considerably large for memory that you should use ReadLine.

叹倦 2024-12-21 13:26:33

尝试这个离线解决方案

StreamReader dr = new StreamReader(@"C:\txt.txt");
string str = dr.ReadToEnd();
string[] p = str.Split(new string[] { Environment.NewLine, " " }, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, int> count = new Dictionary<string, int>();
for (int i = 0; i < p.Length; i++)
{
    try
    {
        count[p[i].Trim()] = count[p[i]] + 1;
    }
    catch
    {
        count.Add(p[i], 1);
    }
}

try this offline solution

StreamReader dr = new StreamReader(@"C:\txt.txt");
string str = dr.ReadToEnd();
string[] p = str.Split(new string[] { Environment.NewLine, " " }, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, int> count = new Dictionary<string, int>();
for (int i = 0; i < p.Length; i++)
{
    try
    {
        count[p[i].Trim()] = count[p[i]] + 1;
    }
    catch
    {
        count.Add(p[i], 1);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文