( I am a beginner with C# ) I wants to create a list of Person class using 2 lists, List of Users and List of Post here is how the class structure looks. Problem : while Creating Object using LINQ, i want that same person object is not created ( ie. with same name, userId, Id ). Is it even Possible using LINQ ? ( i am using System.linq )
class User
{
public string Id { get; set; }
public string Name { get; set; }
}
class Post
{
public string Id { get; set; }
public string UserId { get; set; }
public string Text { get; set; }
}
class Person
{
public string Name { get; set; }
public string Id { get; set; }
public string UserId { get; set; }
public List<string> listOfPosts { get; set; }
public Person(string Id , string Name , string UserId)
{
this.Name = Name;
this.Id = Id;
this.UserId = Id;
}
}
class Test
{
static void Main()
{
List<User> userList = UserRepository.GetUsers(); // sample data
List<Post> postList = PostRepository.GetPosts(); // sample data
/*
* i want to create List of Person where person will contain UserId, ID,
* name , listOfPost(list<string> - containg all the post of user)
* this is the code is wrote for creating new person, but how will i populate
* person's listOfPost ?
* what changes do i need to make in person class ?
* what changes should i do so that same person object is not created (same userId, Id, name) and contins List of post?
*
* one approach what i thought is - to remove duplicates by merging objects using loops.
* can i do this using LINQ ?
* Or Is it even possible ?
*
*/
List<Person> personList = (from u in userList
from p in postList
where u.Id == p.UserId
select (new Person(u.Id, u.Name, p.UserId))
).ToList<Person>();
// if i go by this logic then this creates duplicate objects ( same name, id, UserId , but with diff text ),
// ( after modifying constructor and passing p.Text )
}
}
I tried writing logic, googling it up, looking over other stackOverflow question, but was not able to find/understand how to approach this problem. I am a beginner with C#, less than (20 days of exp).