I have one master table Category.
ID | Name
----------
1 | Category1
2 | Category2
3 | Category3
4 | Category4
And Another Table Details have field like
ID | CategoryId | Detail
--------------------
1 | 1,2,3 | Test1
2 | 3,4 | Test2
Here the Category Id stored as comma separated values.
Now i want the result as
ID | CategoryName
----------------
1 | Category1,Category2,Category3
2 | Category3,Category4
AnyOne Have idea ..??
You can use link this:
private static void commaSeperate(List<classname> obj)
{
string delimeter = ",";
Console.WriteLine(obj.Aggregate((i, j) => new classname { Name = (i.Name + delimeter + j.Name) }).Name);
Console.ReadKey();
}
This is just a sample, please modify according to your conditions.
Hope this will help you.
This could be the solution if our retrieve the data into memory first.
var q = from d in Details
from m in Master
select new {Id = d.Id, CategoryName = String.Join(m.Where(i=> d.CategoryId.Split(',').Cast<int32>().Contains(i.Id).Select(i => i.Name).ToArray(), ',')}
You can't join these two tables but I think below query would work for your result:
(from de in datacontextobj.Details
from ca in datacontextobj.Category
where de.CategoryId.Contains(ca.ID)
select de.ID, ca.Name).ToList();
Related
List 1:
| User Id | Latest |
+---------------------+------------------+
| 1 | 1 |
| 2 | 3 |
| 3 | 3 |
| 4 | 0 |
List 2:
| User Id | Latest | Rating |
+---------------------+------------------+------------------+
| 1 | null | 10 |
| 2 | null | 12 |
| 3 | null | 11 |
| 4 | null | 16 |
I want to insert the values of the Latest column of List1 into the Latest column of List2 based on joining/comparing values of the User Id column in both lists.
I can use a foreach loop but that would run n*m I guess and look ugly. Is there a way to do it with LINQ or efficiently?
Regards.
Junaid
var result = from i1 in List1
join i2 in List2
on i1.UserId equals i2.UserId
select new
{
i2.UserId,
i1.Latest,
i2.Rating
};
you can do it with LINQ :
Try this code :
List2.ForEach(item1 =>
{
item1.Latest = List1.FirstOrDefault(item2 => item2.UserId == item1.UserId)?.Latest;
});
Note That, Latest must be Nullable.
LINQ will never change any of the source sequences, it can only extract data from it.
You will have to enumerate over the extracted data to update your original tables.
var recordsToUpdate = List2.Join(List1, // join List2 and List1
list2Row => list2Row.UserId, // from every row in List2 take UserId
list1Row => list1Row.UserId, // from every row in List1 take UserId
(list2Row, list1Row) => new // when they match make one new object
{
Id = list2Row.UserId, // take UserId from list2
Latest = list1Row.Latest, // take Latest from list1
Rating = list2Row.Rating, // take Rating from list2
})
.ToList(); // execute the query
I don't know how you update your records. Entity framework? SQL? it will be something like this:
foreach (var recordToUpdate in recordsToUpdate)
{
UpdateRecord(recordToUpdate.UserId, recordToUpdate.Latest, recordToUpdate.Rating)
// TODO: implement this function
}
Try something like this. this may fix your issue with adding the Latest value from List1 to List2.
List2.AddRange(List1.Select(user => new List1{
Latest = user.Latest,
UserID = user.UserID
}));
I know that there are some examples but I could not apply them on my code. I am pretty new to Linq and SQL. I have two tables I want to join.
First Table:
--------------
| Id | Count |
--------------
| 1 | 10 |
--------------
| 2 | 4 |
--------------
Second Table:
--------------
| Id | Name |
--------------
| 1 | Tom |
--------------
| 2 | John |
--------------
| 3 | Nick |
--------------
| 4 | Max |
--------------
As you can see, the second table has more records than the first. My goal is to join them based on the Id. The problem is that after I have joined the tables it only displays the matching records, which is Id 1 and 2. Though I want to display every Id (from 1 to 4) and if there is no match in both tables, there should be a default value 0.
It should look like this:
----------------------
| Id | Name | Count |
----------------------
| 1 | Tom | 10 |
----------------------
| 2 | John | 4 |
----------------------
| 3 | Nick | 0 |
----------------------
| 4 | Max | 0 |
----------------------
So far I have got this code:
// first table
var listCount = entity.tblKundes.Where(x => x.Studio == 2)
.Select(x => new { x.Id, x.Name})
.GroupBy(x => x.Name).ToList();
// second table
var listBerater = entity.tblUsers.Where(x => x.Studio == 2)
.Select(x => new { x.Id, x.Name})
.ToList();
// This join should be edited so that it displays non matching records as well
var test = listCount.Join(
listBerater,
count => count.Key,
berater => berater.Id,
(count, berater) => new { listCount = count, listBerater = berater }
).ToList();
Edit:
var test2 = (from list in listCount
join berater in listBerater on list.Berater equals berater.Id into gj
from sublist in gj.DefaultIfEmpty()
select new { sublist.Id, sublist.Nachname, sublist.Vorname }).ToList();
There is a typical concept in every Structured Query Languages which is called "Left join". Left-Join means that you will have all rows of data from first table even there is no equivalent in the second one. "Inner-Join" is a little different and only looks for matched rows of data.
Here you can find enough and complete information about your issue.
Left Join
I have five Models (tables). I want to select all trainings which Venue_Distrcit is accessible by user whose ID is 1. But I prefer if can be solved with .Contains like firstTrainingSet. Also I have practiced with .Foreach but can't fix the proper format.
1. TRAINING 2. TRAINING_VENUE 3. DISTRICT
| ID | NAME | VENUE_ID | | ID | NAME | DCODE | | DCODE | NAME |
4. TRAINING_USER 5.TRAINING_USER_DISTRICT_MAPPING
|ID | NAME | | ID | USER_ID | DCODE|
var TRAINING_USER_ACCESSIBLE_DISTRICT_LIST =
(from trainingUserDistrictMappingTable in db.TRAINING_USER_DISTRICT_MAPPING
where (trainingUserDistrictMappingTable.TRAINING_USER_ID == 1)
select trainingUserDistrictMappingTable).ToList();
var trainingSet = db.TRAINING.Where(x => TRAINING_USER_ACCESSIBLE_DISTRICT_LIST.DCODE
.Contains(x.TRAINING_VENUE.DCODE));
Here I need trainingSet. And x.TRAINING_VENUE.DCODE means that x is TRAINING parameter and x.TRAINING_VENUE can be fetched because VENUE_ID of TRAINING table is foreign key from VENU table ID, and x.TRAINING_VENUE.DCODE is DOCDE from venue table. Which is actually primary key of DISTRICT table. TRAINING_USER_ACCESSIBLE_DISTRICT_LIST is list from DISTRICT table. The thing I can not do is TRAINING_USER_ACCESSIBLE_DISTRICT_LIST.DCODE.Contains(x.TRAINING_VENUE.DCODE).
As you TRAINING_USER_ACCESSIBLE_DISTRICT_LIST is collection so the expression should be:
var trainingSet = db.TRAINING
.Where(x => TRAINING_USER_ACCESSIBLE_DISTRICT_LIST
.Any(y => y.DECODE == x.TRAINING_VENUE.DCODE));
This will fix your issue.
I have the following table (table A):
ID | Data |
1 | Data1 |
2 | Data2 |
3 | Data3 |
4 | Data4 |
I have table B that has 1 row:
DummyID | Dummy |
1 | Dummy1 |
I have to join table A with table B in the following way:
ID | Data |DummyID | Dummy |
1 | Data1 |1 | Dummy1 |
2 | Data2 |1 | Dummy1 |
3 | Data3 |1 | Dummy1 |
4 | Data4 |1 | Dummy1 |
Obviously I can't use any ID in the on clause.
from item in context.TableA
join dummy in context.TableB on ? = ?
select new
{
RowA=item,
Dummy=dummy
}
How could I do that with LINQ?
That's a cross join which you can get via Linq in the following way
from item in context.TableA
from dummy in context.TableB
select new
{
RowA=item,
Dummy=dummy
}
Or the following in method syntax
context.TableA.SelectMany(
item => context.TableB.Select(dummy => new { RowA = item, Dummy = dummy }));
Note that if TableB every has more than one row you'll end up with N times M rows where N is the number of rows in TableA and M is the number of rows in TableB.
No need to join at all.
from item in context.TableA
select new
{
RowA = item,
Dummy = context.TableB.FirstOrDefault()
}
Having said that, I'd have to question why you're doing this. The idea of LINQ is to get your relational data into an object-oriented form. Why not just retrieve the TableB information once and do whatever processing you need to do in-memory? It would reduce the size of the payload you're transferring from the database back to the application.
Why do you want to use join. You want to use each item in your old sequence to create a different item in your new sequence. In LINQ you would use Enumerable.Select for this:
var dummy = context.Dummy.FirstOrDefault();
var newSequence = context.TableA
.Select(itemInTableA =>
new
{
RowA = itemInTableA,
Dummy = dummy,
});
I have "Orders" table where its primary key is "OrderId ":
OrderId | OrderName
------- | ----------
1 | Order X
2 | Order Y
3 | Order Z
and "OrderDetails" table where its primary key is "OrderDetailsId " foreign key is 'OrderId":
OrderDetailsId | OrderId | ItemId | DeliveryDate
-------------- | ------- | ------ | ------------
10 | 1 | AA | 1/1/2010
20 | 1 | BB | 1/1/2013
30 | 2 | CC | 1/1/2012
40 | 2 | CC | 1/1/2014
Each order has ZERO or more order details, each order detail has specific delivery date.
We want to get all the orders, whether they have order details or not, and mark just one order as VIP if it has the order detail that has the maximum "delivery date"
This is the expected output:
OrderId | OrderName | IsVIP
------- | --------- | -----
1 | Order X | NO
2 | Order Y | YES
3 | Order Z | NO (since it has no order details)
That's because the maximum delivery date is for OrderDetailsId = 40 which belongs to OrderId = 2
How to accomplish this using the most readable LINQ code
I am not sure if you have OrderDetails property in orders collection (if so then #juharr's answer is correct). But, if they are not then you can make use of group join like this:-
var result = from o in orders
join od in orderDetails
on o.OrderId equals od.OrderId into g
select new {
OrderId = o.OrderId,
OrderName = o.OrderName,
IsVIP = g.Any(x => x.DeliveryDate == orderDetails.Max(z => z.DeliveryDate))
? "Yes" : "No"
};
Here is an example Fiddle with linq-to-objects.
Use navigation properties. Note this will set IsVIP to "YES" for all orders that contain an order detail with the max delivery date.
var query = from order in db.Orders
select new
{
order.OrderId,
order.Name,
IsVIP = order.OrderDetails.Any(
od => od.DeliveryDate == db.OrderDetails.Max(x => x.DeliveryDate))
? "YES"
: "NO"
};