0

I have an object with the following Properties

public class Name
{
    public string FirstName 
    {
        get;
        set;
    }
    public string LastName
    {
        get;
        set;
    }

}

I get a list of Name Object as NameList which contains two objects as item

I want to compare these two objects in the list to get the object which has same FirstName. I have been looking for a solution for past 2 hours.

In the List of Name object I get two Name objects as

ListItem 1: FirstName : Steve ; LastName : Rogers;

ListItem 2 : FirstName : Steve ; LastName : David;

What i want is to compare these to list Items check if the FirstName Properties are same

5
  • 2
    Can you provide an example of your data Your question isn't quite clear. Are you saying you have List<Name> which contains just two Name objects? It isn't clear what you mean by "get the object which has same FirstName" because a single object can't have a "same firstname" (same as what?) Commented May 16, 2015 at 13:32
  • As per my understanding, I think you have a single list and you want to check items with same name inside that list. So you should try grouping... Commented May 16, 2015 at 13:36
  • I have updated the question. please check and let me know Commented May 16, 2015 at 13:37
  • @Eterm I think he has one list with some Name objects. He want to get all Name objects which has the same FirstName as another Listitem Commented May 16, 2015 at 13:37
  • Ok, so a group by then filtering the groups so they have count > 1 should do it. Commented May 16, 2015 at 13:41

2 Answers 2

1

If you are looking to get all objects with the same FirstName you should be using GroupBy:

var groups = NameList.GroupBy(li => li.FirstName);
Sign up to request clarification or add additional context in comments.

Comments

1

You want to find all duplicates.

var duplicates = NameList.GroupBy(o => o.FirstName).Where(g => g.Skip(1).Any()).SelectMany(g => g);  

7 Comments

Seems like you understood it wrong :) OP made an edit, check it out
Please check the updated question. hope you understood the query
@Simon Updated answer to get all objects with duplicate firstnames.
@Midhun Please see updated solution. This gets all duplicates.
Sorry for Asking again.. is there any way to check this for immediate preceding listitem?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.