LINQ Join 2 List<T>s - c#

Preface: I don't understand what this does:
o => o.ID, i => i.ID, (o, id) => o
So go easy on me. :-)
I have 2 lists that I need to join together:
// list1 contains ALL contacts for a customer.
// Each item has a unique ID.
// There are no duplicates.
ContactCollection list1 = myCustomer.GetContacts();
// list2 contains the customer contacts (in list1) relevant to a REPORT
// the items in this list may have properties that differ from those in list1.
/*****/// e.g.:
/*****/ bool SelectedForNotification;
/*****/// may be different.
ContactCollection list2 = myReport.GetContacts();
I need to create a third ContactCollection that contains all of the contacts in list1 but with the properties of the items in list2, if the item is in the list[2] (list3.Count == list1.Count).
I need to replace all items in list1 with the items in list2 where items in list1 have the IDs of the items in list2. The resulting list (list3) should contain the same number of items at list1.
I feel as though I'm not making any sense. So, please ask questions in the comments and I'll try to clarify.

Joins are not so difficult, but your problem could probably use some further explanation.
To join two lists, you could do something like
var joined = from Item1 in list1
join Item2 in list2
on Item1.Id equals Item2.Id // join on some property
select new { Item1, Item2 };
this will give an IEnumerable<'a>, where 'a is an anonymous type holding an item from list1 and its related item from list2. You could then choose which objects' properties to use as needed.
To get the result to a concrete list, all that is needed is a call to .ToList(). You can do that like
var list3 = joined.ToList();
// or
var list3 = (from Item1 in list1
join Item2 in list2
on Item1.Id equals Item2.Id // join on some property
select new { Item1, Item2 }).ToList();
To do a left join to select all elements from list1 even without a match in list2, you can do something like this
var list3 = (from Item1 in list1
join Item2 in list2
on Item1.Id equals Item2.Id // join on some property
into grouping
from Item2 in grouping.DefaultIfEmpty()
select new { Item1, Item2 }).ToList();
This will give you a list where Item1 equals the item from the first list and Item2 will either equal the matching item from the second list or the default, which will be null for a reference type.

Here is what I came up with (based on this):
List<Contact> list3 = (from item1 in list1
join item2 in list2
on item1.ContactID equals item2.ContactID into g
from o in g.DefaultIfEmpty()
select o == null ? item1 :o).ToList<Contact>();
My favorite part is the big nosed smiley
:o)
Thanks for your help!

Here is a DotNetFiddle with a Linq Group Join
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Order
{
public int Id;
public string Name;
public Order(int id, string name)
{
this.Id = id;
this.Name = name;
}
}
class OrderItem
{
public int Id;
public string Name;
public int OrderId;
public OrderItem(int id, string name, int orderId)
{
this.Id = id;
this.Name = name;
this.OrderId = orderId;
}
}
List<Order> orders = new List<Order>()
{
new Order(1, "one"),
new Order(2, "two")
};
List<OrderItem> orderItems = new List<OrderItem>()
{
new OrderItem(1, "itemOne", 1),
new OrderItem(2, "itemTwo", 1),
new OrderItem(3, "itemThree", 1),
new OrderItem(4, "itemFour", 2),
new OrderItem(5, "itemFive", 2)
};
var joined =
from o in orders
join oi in orderItems
on o.Id equals oi.OrderId into gj // gj means group join and is a collection OrderItem
select new { o, gj };
// this is just to write the results to the console
string columns = "{0,-20} {1, -20}";
Console.WriteLine(string.Format(columns, "Order", "Item Count"));
foreach(var j in joined)
{
Console.WriteLine(columns, j.o.Name, j.gj.Count() );
}

It looks like you don't really need a full-join. You could instead do a semi-join, checking each contact in list 2 to see if it is contained in list 1:
ContactCollection list3 = list2.Where(c => list1.Contains(c));
I don't know how big your lists are, but note that this approach has O(nm) complexity unless list1 is sorted or supports fast lookups (as in a hashset), in which case it could be as efficient as O(nlog(m)) or rewritten as a merge-join and be O(n).

Related

How to compare two lists with multiple objects and set values?

I have two lists. Each list has a Name object and and a Value object. I want to loop through list1 and check if each list1 Name object is the same as the list2 Name object (the linq code below does this).
If they match, then I want the List1 Value to be set with the list2 Value How can this be done?
list1 list2
Name Value Name Value
john apple John orange
peter null Peter grape
I need it to look like this:
list1 list2
Name Value Name Value
john orange john orange
peter grape peter grape
Linq code:
var x = list1.Where(n => list2.Select(n1 => n1.Name).Contains(n.Name));
For filtering you can use LINQ, to set the values use a loop:
var commonItems = from x in list1
join y in list2
on x.Name equals y.Name
select new { Item = x, NewValue = y.Value };
foreach(var x in commonItems)
{
x.Item.Value = x.NewValue;
}
In one result, you can get the objects joined together:
var output= from l1 in list1
join l2 in list2
on l1.Name equals l2.Name
select new { List1 = l1, List2 = l2};
And then manipulate the objects on the returned results. by looping through each and setting:
foreach (var result in output)
result.List1.Value = result.List2.Value;
You are looking for a left join
var x = from l1 in list1
join l2 in list2 on l1.Name equals l2.Name into l3
from l2 in l3.DefaultIfEmpty()
select new { Name = l1.Name, Value = (l2 == null ? l1.Value : l2.Value) };

Manipulate two list of objects in c#

I have an objectA with an ID property and a Status property.
I have a ListA which is a collection of objectA.
I also have an objectB with an ID property and a Status property.
I have a ListB which is a collection of objectB.
I need to match listA collection with listB collection based on ID and if there is a match update the Status from ListB to ListA.
What is the best way to do this without foreach loop?
Thanks for the help.
You can use LINQ for this:
var objectsForUpdate = (from a in listA
join b in listB
on a.Id equals b.Id
select new { a, b });
foreach (var obj in objectsForUpdate)
{
obj.a.Status = obj.b.Status;
}
Note this cannot be achieved without using the foreach statement.
I had a similar scenario. I had cartProducts and productsPurchasePrices.
I used linq to join the two collections:
//join currentCart...
var p = currentCart.Rows.Join(
productsPurchasePrices, //... with productsPurchasePrices
row => row.ProductCode, //first collection key
purchasePrice => purchasePrice.Key, //second collection key
(row, purchasePrice) => new
{
productCode = row.ProductCode,
productMargin = purchasePrice.ProductMargin
});
References:
http://msdn.microsoft.com/en-us/library/bb397941.aspx
http://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9

join two list in linq initializing properties one time

I have found many examples to join list in linq but my exact problem is not solved.
I have to join list List and List
i have initialized all properties of List and when joining i have to again initialize all properties of A and added properties from B.
List<A> listB = from c in country
select new A
{
CountryId=c.CountryId
CountryName=c.CountryName
} ;
List<A> listA = from d in data
select new A
{
Name = d.Name
Age= d.Age,
City=d.City,
CountryId=d.CountryId
} ;
now to initialize Country property in List i am joining both list
here the problem starts
listA = from d in listA
join c in listB on d.CountryId=c.CountryId
select new A
{
Name = d.Name
Age= d.Age,
City=d.City,
Country=c.CountryName
} ;
see in above join i have to again initialize Name, Age and City What i can do to initialize properties at one place.
Do not use listA and listB - join countries and data directly:
from c in country
join d in data
on c.CountryId equals d.CountryId
select new A {
Name = d.Name
Age = d.Age,
City = d.City,
Country = c.CountryName
};
BTW why do you use A class for listA and listB if both contain different data? It should be two different classes.

c# where in with list and linq

I have two lists, one have a list of object A an other a list of objects B, like this:
ObjectA
{
Int64 idObjectA;
String name;
....
}
ObjectB
{
Int64 idObjectB;
Int64 idObjectA;
String name;
....
}
I have two list, one with Object A and other with Object B. I want to create a new list C that have only objects B, which IDObjectA is any ID of the list A.
In SQL it would be somthing line that:
select * from B where IDObjectA IN(1,2,3,4...);
In my case, the list of values for the IN clause is the list of ObjectA, which have the property idObjectA.
You can use the Join linq method to achieve this by joining listB and listA by their idObjectA, then select itemB.
var result = (from itemB in listB
join itemA in listA on itemB.idObjectA equals itemA.idObjectA
select itemB).ToList();
This method has a linear complexity (O(n)). Using Where(... => ....Contains()) or double foreach has a quadratic complexity (O(n^2)).
The same with Join and without Contains:
var listC = listB.Join(listA, b => b.ObjectAId, a => a.Id, (b, a) => b).ToList();
This is slightly different way of doing it as opposed to a join.
List<ObjectA> listA = ..
List<ObjectB> listB = ..
int[] listAIds = listA.Select(a => a.idObjectA).ToList();
//^^ this projects the list of objects into a list of ints
//It reads like this...
//get items in listB WHERE..
listB.Where(b => listAIds.Contains(b.idObjectA)).ToList();
//b.idObjectA is in listA, OR where listA contains b.idObjectA
Not linq, but does what you want it to:
List<ObjectB> C = new List<ObjectB>();
foreach (n in B)
{
foreach (c in A)
{
if (n.idObjectA == c.idObjectA)
{
C.Add(n)
break;
}
}
}
Or if you wanted higher performance, use a for, and higher than that use Cédric Bignon's solution.

Acces data from objects in a list

Hi I am trying to convert a a LINQ query result into a list of objects and I seem to be doing something wrong because I can not acces the properties of each object.Here is my code:
List<Object> productList = new List<Object>();
var products = (from p in Products
join s in SubCategories on p.SubcatId equals s.SubCatId
join b in Brands on p.BrandId equals b.BrandId
select new
{
Subcategory = s.SubCatName,
Brand = b.BrandName,
p.ProductName,
p.ProductPrice
}).Where(x => x.Subcategory == subcategory);
foreach (var product in products)
{
productList.Add(product);
}
foreach (var produs in productList){
Console.WriteLine(produs.ProductName);
}
When I try to do this I get an error that says:
Object does not contain a definion for ProductName
The same goes for all the other fields two
Aldo if I try and do this:
Console.WriteLine(produs);
I get tables with the data for each field
I have run this for tests on LINQPAD and it also does not work in visual studio.What am I doing wrong?
This is the problem:
List<Object> productList = new List<Object>();
You're declaring it as a List<object>, which means when you later write this:
foreach (var produs in productList)
Then produs is implicitly typed as object.
The simplest approach would be just to use ToList() instead of copying the results to a list yourself:
var products = (from p in Products
join s in SubCategories.Where(x => x.SubCatName == subcategory)
on p.SubcatId equals s.SubCatId
join b in Brands on p.BrandId equals b.BrandId
select new {
Subcategory = s.SubCatName,
Brand = b.BrandName,
p.ProductName,
p.ProductPrice
}).ToList();
Note that I've moved the subcategory name filter as early as possible - there's no need to do it after the join. The ToList() call at the end will mean the result is a List<T> where T is your anonymous type.
Then you can use:
foreach (var product in products)
{
Console.WriteLine(produs.ProductName);
}
use
List<Product> productList = new List<Product>();
instead of
List<Object> productList = new List<Object>();
where Product is the unit of Products
A List of Object means that you only get the methods contained within an object. You should do something like:
List<Product> productList = new List<Product>();
Just as a note you can also do:
productList = products.ToList<Product>();
instead of iterating over the list and adding each element. (Linq does this for you implicitely).
NOTE: This is assuming that you change your query select to select new Product { ... }
This will then allow you to use List<Product> productList so that you can pass your Product list to other methods etc.

Categories