Skip to content

Instantly share code, notes, and snippets.

@mshwf
Last active March 5, 2018 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mshwf/0b42fe2fac860c7b6beb4ea7214f141d to your computer and use it in GitHub Desktop.
Save mshwf/0b42fe2fac860c7b6beb4ea7214f141d to your computer and use it in GitHub Desktop.
class MyClass
{
public int RowNo { get; set; }
public int Value { get; set; }
}
public static class LinqEx
{
public static IEnumerable<T> Project<T>(this IEnumerable<T> lst1,
IEnumerable<T> lst2, Func<T, object> id, Action<T, T> action)
{
if (lst2.Count() > lst1.Count())
throw new Exception("Projected list's count must be greater than " +
"or equal to the other list.");
var sortedList1 = lst1.OrderBy(id).ToList();
var sortedList2 = lst2.OrderBy(id).ToList();
for (int i = 0; i < lst2.Count(); i++)
{
action(sortedList1[i], sortedList2[i]);
}
return sortedList1;
}
}
public class Example12_4
{
public static void Main()
{
var List1 = new List<MyClass>
{
new MyClass { RowNo = 1, Value = 11},
new MyClass { RowNo = 2, Value = 22 },
new MyClass { RowNo = 3, Value = 33},
new MyClass { RowNo = 4, Value = 88 }
};
var List2 = new List<MyClass>
{
new MyClass { RowNo = 1, Value = 44},
new MyClass { RowNo = 2, Value = 55},
new MyClass { RowNo = 3, Value = 66 }
};
var lst = List1.Project(List2, x => x.RowNo, (y, z) => { y.Value = z.Value; });
foreach (var item in lst)
{
Console.WriteLine($"{item.RowNo}, {item.Value}");
}
}
@asd007
Copy link

asd007 commented Mar 5, 2018

var List1 = new List
{
new MyClass { RowNo = 1, Value = 11},
new MyClass { RowNo = 2, Value = 22 },
new MyClass { RowNo = 3, Value = 33},
new MyClass { RowNo = 4, Value = 88 }
};

        var List2 = new List<MyClass>
    {
        new MyClass { RowNo = 1, Value = 44},
        new MyClass { RowNo = 3, Value = 66 }
    };

@asd007
Copy link

asd007 commented Mar 5, 2018

you were right about me doing things "wrongly", I was using a struct to store the values, as I believe it should be

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment