get the distinct element(eg: ID) from student detail where collection of student details are inside another array using C#

Viewed 31

//Model

public class StudentDetails
    {
            
            public int Contact { get; set; }
            public string Summary { get; set; }
            public string Address { get; set; }
            public long ID { get; set; }
    
        }

//controller

public async Task AddStudDetails([FromBody] StudentDetails[] studentDetails){}

2 Answers

You could use LINQ to do this:

var distinctResults = studentDetails.DistinctBy(student => student.ID).ToArray();

This'll yield an array of all the students where no two students have the same ID.

you'd also have to add a using System.Linq; to your imports :)

Edit

if you have a StudentDetails[][] as an input (array of arrays of StudentDetails) and you still want to use LINQ then this would be one way of doing it

StudentDetails[][] myArrArr = ...;
myArrArr
    .Aggregate(new List<StudentDetails>(), (resultList, studentDetails) => resultList
        .Concat(studentDetails)
        .DistinctBy(s => s.ID)
        .ToList());

however using a simple dictionary may be faster and less resource intensive

StudentDetails[][] myArrArr = ...;
Dictionary<long, StudentDetails> distinctStudents = new();
foreach (StudentDetails[] array in myArrArr)
{
    foreach (StudentDetails details in array)
    {
        distinctStudents.TryAdd(details.ID, details);
    }
}
var result = distinctStudents.Values.ToArray();

Edit 2

I think I finally understood your question, if you just want to extract a single property of a collection of objects you could just do a simple Select()

var allIds = studentDetails.Select(student => student.ID).ToArray();
var stud = from s in studentDetails select s.ID;

figured out the code I was looking for. Hope this will be helpful to others too.

Related