Share via

Using Linq

Ronald Rex 1,671 Reputation points
2023-06-16T16:46:47.0766667+00:00

I have these two collections, Source and Target. Isnt there a Linq construct that I can use where I am not having to traverse over the second collection Target or that I can just find the value in the Target Collection. Thanks !!

public void DoNotify(UserDefinedFields input)
	{
		var Source = input.GetType().GetProperties();
		var Target = this.GetType().GetProperties();
		foreach (var sourceProp in Source)
		{
			foreach (var targetProp in Target)
			{
				if (sourceProp.Name == targetProp.Name)
				{
					targetProp.SetValue(this, sourceProp.GetValue(input));
					break;
				}
			}
		}
	}
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

P a u l 10,766 Reputation points
2023-06-16T17:12:00.15+00:00

You could use LINQ Join:

var person1 = new Person("1", "Paul");
var person2 = new Person("2", "John");
var person3 = new Person("3", "Jess");

var list1 = new[] { person1, person2, person3 };
var list2 = new[] { person1, person2 };

var joined = list1.Join(inner: list2,
	outerKeySelector: p1 => p1.Id,
	innerKeySelector: p2 => p2.Id,
	resultSelector: (p1, p2) => new { First = p1, Second = p2 }
);

foreach (var pair in joined) {
	Console.WriteLine($"{pair.First.FirstName} -> {pair.Second.FirstName}");
}

record Person(string Id, string FirstName);

Produces:

Paul -> Paul

John -> John

You'd just want to join by Name instead of Id. This is equivalent to an INNER JOIN in SQL.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.