简体   繁体   English

使用'Distinct()'时仍然得到重复的字符串

[英]Still get repeated strings when using 'Distinct()'

Um I am working on a school project.嗯,我正在做一个学校项目。 I know its not professional to ask for homework questions, but I am really unsure about this part (was not gone through in class).我知道问家庭作业问题不专业,但我真的不确定这部分(在课堂上没有完成)。 So I came to my last resort of asking here.所以我来到了我在这里问的最后手段。 So situation is a comparison between two list has to be made, and then print out similar elements.所以情况是必须在两个列表之间进行比较,然后打印出相似的元素。

Current code:当前代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LessonXEx4
{
    class Student
    {
        public string strName;
        public float fltGPA;
        public Student(string x, float y)
        {
            strName = x;
            fltGPA = y;
        }
    }

    class Program
    {
        static void DisplayStudents(List<Student> Studentx)
        {
            foreach(Student C in Studentx)
            {
                Console.WriteLine("Student name: " + C.strName + "\nGPA: " + C.fltGPA);
            }
        }
        static List<Student> AddStudentInfo()
        {
            List<Student> Studlist = new List<Student>();
            Student ObjStd;
            string Per = "Y";   
            while (Per == "Y")
            {
                Console.WriteLine("Enter student Name:");
                string N = Console.ReadLine();

                Console.WriteLine("Enter you GPA: ");
                float G = float.Parse(Console.ReadLine());

                ObjStd = new Student(N, G);
                Studlist.Add(ObjStd);

                Console.WriteLine("Do you want to continue: ");
                string Perx = Console.ReadLine();
                Per = Perx;
            }
            return Studlist;
        }
        static void Main(string[] args)
        {
            List<Student> studentlist1 = new List<Student>();
            List<Student> studentlist2 = new List<Student>();
            Console.WriteLine("Group 1:\n");
            studentlist1 = AddStudentInfo();
            Console.WriteLine("\n\nGroup 2:\n");
            studentlist2 = AddStudentInfo();
            Console.WriteLine("\n\nGroup 1:\n");
            DisplayStudents(studentlist1);
            Console.WriteLine("\n\nGroup 2:\n");
            DisplayStudents(studentlist2);
            foreach (Student Fx in studentlist1)
            {
                foreach (Student fX in studentlist2) 
                {
                    if (Fx.fltGPA == fX.fltGPA)
                    {
                        List<String> Nam = new List<string>();
                        Nam.Add(fX.strName);
                        Nam.Add(Fx.strName);
                        Nam.Distinct().ToArray();
                        Console.WriteLine("\n" + fX.fltGPA);
                        Nam.ForEach(item => Console.WriteLine(item));
                    }
                }
            }
                        Console.ReadLine();
        }
    }
}

Current output:当前 output:

Group 1:

Enter student Name:
qw
Enter you GPA:
12
Do you want to continue:
Y
Enter student Name:
we
Enter you GPA:
12
Do you want to continue:
Y
Enter student Name:
er
Enter you GPA:
12
Do you want to continue:
N


Group 2:

Enter student Name:
as
Enter you GPA:
12
Do you want to continue:
Y
Enter student Name:
sd
Enter you GPA:
12
Do you want to continue:
Y
Enter student Name:
df
Enter you GPA:
12
Do you want to continue:
n


Group 1:

Student name: qw
GPA: 12
Student name: we
GPA: 12
Student name: er
GPA: 12


Group 2:

Student name: as
GPA: 12
Student name: sd
GPA: 12
Student name: df
GPA: 12

12
as
qw

12
sd
qw

12
df
qw

12
as
we

12
sd
we

12
df
we

12
as
er

12
sd
er

12
df
er

Though I tried .Distinct() in the Nam list, Its still repeating the names.虽然我在Nam列表中尝试.Distinct() ,但它仍然重复名称。 I don't want it to repeat them.我不希望它重复它们。 What I expected is:我的预期是:

12
qw
we
er
as
sd
df

or even better:甚至更好:

Student(s) with GPA of 12 are: qw, we, er, as, sd, df

Something like that.类似的东西。 Any help will be really appreciated.任何帮助将不胜感激。

Thank you for stating it's a homework problem.谢谢你说这是一个家庭作业问题。 You are almost there.你快到了。 Where you write:你写的地方:

Nam.Distinct().ToArray();
Nam.ForEach(item => Console.WriteLine(item));

is where you have a slight problem.是你有一个小问题的地方。 Distinct() does not alter your list. Distinct()不会改变您的列表。 It gives you a result with the distinct values, while leaving the original list intact.它为您提供具有不同值的结果,同时保持原始列表不变。 You would need to save that result and print those values rather than the original list:您需要保存该结果并打印这些值而不是原始列表:

var distinctNames = Nam.Distinct().ToList();
distinctNames.ForEach(item => Console.WriteLine(item));

Though I tried.Distinct() in the Nam list, Its still repeating the names.虽然我在 Nam 列表中尝试过.Distinct(),但它仍然重复名称。 I don't want it to repeat them.我不希望它重复它们。

But, you have a loop inside a loop, so the inner loop will be repeated as many times as there are items in the outer loop但是,您在循环中有一个循环,因此内部循环将重复与外部循环中的项目一样多的次数

If you want to merge studentlist1 and studentlist2 you can just add them all to a new list如果你想合并 studentlist1 和 studentlist2 你可以将它们全部添加到一个新列表中

var allStudents = new List<Student>();

allStudents.AddRange(studentList1);
allStudents.AddRange(studentList2);

Student(s) with GPA of 12 are: qw, we, er, as, sd, df GPA 为 12 的学生是:qw、we、er、as、sd、df

This looks like you want to group students by GPA.这看起来像您想按 GPA 对学生进行分组。 You probably havent been taught LINQ in depth yet (though I see you're using some linq methods) but Dictionary may have been covered您可能还没有深入学习过 LINQ(尽管我看到您正在使用一些 linq 方法),但可能已经涵盖了字典

Dictionary provides a way to map a key to a value.字典提供了一种方法,将 map 一个键转换为一个值。 The key (one of) will be GPA.关键(其中之一)将是 GPA。 Because there will be many values with the same key, we will use a list to hold the values.因为会有许多具有相同键的值,所以我们将使用一个列表来保存这些值。

var d = new Dictionary<float, List<Student>>();

foreach(var s in allStudents){
  //ensure the dictionary knows of this gpa value
  if(!d.ContainsKey(s.fltGpa))
    d[s.fltGpa] = new List<Student>();

  //add the student to the list of students mapped to this GPA
  d[s.fltGpa].Add(s);
}

Now you have a dictionary that has lists per different gpa.现在你有一个字典,其中包含每个不同 gpa 的列表。 If you had 2 students with a gpa of 4 and 1 student with a gpa of 5 your Dictionary would be like:如果您有 2 名 gpa 为 4 的学生和 1 名 gpa 为 5 的学生,您的字典将如下所示:

d[4] -> { Student, Student }
d[5] -> { Student }

The dictionary is effectively a list of KeyValuePair<float, List<Student>> ie a list of lists - something you can use two loops on:字典实际上是KeyValuePair<float, List<Student>>的列表,即列表列表 - 您可以使用两个循环:

foreach(var kvp in d) // for every keyvaluepair
{
  Console.WriteLine("Students with a GPA of " + kvp.Key); //Key is a float of the gpa

  foreach(var s in kvp.Value) //value is a List<Student>
    Console.Write(s.strName + " ");
}
  

Once you understand this it puts you in good stead to understanding grouping in linq.一旦你理解了这一点,你就可以很好地理解 linq 中的分组。 A group operation produces a result where it's like a bunch of lists and every list has a Key property that is what all the elements in the list were grouped on分组操作会产生一个结果,它就像一堆列表,每个列表都有一个 Key 属性,该属性是列表中所有元素的分组依据

var groups = allStudents.GroupBy(st = st.fltGpa);

This is somewhat similar to the loop that prepares the dictionary.这有点类似于准备字典的循环。 groups is like an array of lists (I'm calling them something different do I can refer to them more easily), every item in the inner list is a student,and the inner list has a Key that is the gpa of every student in the inner list. groups就像一个列表数组(我称它们为不同的东西,我可以更容易地引用它们吗),内部列表中的每个项目都是一个学生,并且内部列表有一个 Key,它是每个学生的 gpa内部列表。 In the outer array there is one list per different gpa, this means for four students, three that have gpa 4 and one that has gpa 5, would become an array of size two (two different gpa values), the first element in the array is a list of length 3 and Key of 4 (three students have a gpa of 4).在外部数组中,每个不同的 gpa 都有一个列表,这意味着对于四个学生,三个 gpa 4 和一个 gpa 5,将成为一个大小为 2 的数组(两个不同的 gpa 值),数组中的第一个元素是一个长度为 3 且密钥为 4 的列表(三个学生的 gpa 为 4)。 The second element in the array is a list of length 1 and Key of 5 (one student has a gpa of 5)数组中的第二个元素是长度为 1 且 Key 为 5 的列表(一名学生的 gpa 为 5)

These things aren't actually arrays and lists but ultimately they look like a dictionary we saw before - in essence a way of collecting together all the students that have the same gpa into one list, and having a list per different gpa这些东西实际上并不是 arrays 和列表,但最终它们看起来像我们之前看到的字典 - 本质上是一种将所有具有相同 gpa 的学生收集到一个列表中的方法,并且每个不同的 gpa 都有一个列表

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

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