I have following tables
**Track Table**
+---------------+---------------+--------------------+
| TrackId | TrackName | Path |
+===============+===============+====================+
| 1 | jb | http://domain/1.mp3|
+---------------+---------------+--------------------+
| 2 | remix | http://domain/2.mp3|
+---------------+---------------+--------------------+
**Favorite Table**
+---------------+---------------+--------------------+
| favoriteId | ProfileId | TrackId |
+===============+===============+====================+
| 10 | 2130 | 1 |
+---------------+---------------+--------------------+
| 11 | 2132 | 2 |
+---------------+---------------+--------------------+
I need to select tracks into a model where I have to include a boolean field IsFavorite.
Right now my logic is as follows:
1.Select Tracks
2.Select all favorites by profile
3.Iterate to both list and fill field "IsFavorite"
Is there any better method that can work out the same?
Following is my current logic code
Var ActiveTracks = jukeboxTrackService.GetActiveTracks();
var UserFavorites = jukeboxTrackService.GetFavoritesByProfile(ProfileId);
foreach (var item in ActiveTracks )
{
foreach (var fav in UserFavorites)
{
if (item.JukeBoxTrackId == fav.TrackId)
{
item.IsFavorite = true;
}
}
}
return ActiveTracks ;
Thanks in advance.
(from tr in ActiveTracks
join usrfav in UserFavorites on tr.TrackId equals usr.TrackId into UsrTracks
from usrtr in UsrTracks.DefaultIfEmpty()
select new Track
{
IsFavorite = (usrfav.TrackId == null) ? false : true
}
Related
I'm having issues with a program I'm developing. The basic essence of the program is to look through a file of election data and organize it via nested objects. For example, each individual Political Race is an object, and each Political Race object has a list of Candidate and County Results objects and so on.
My current issue revolves around the previously mentioned County Results object. I'm supposed to iterate through the file, and record the Candidate's name and the number of votes they got for each county. Currently I am using nested Ordered Dictionaries to achieve this, but it seems clunky and I am having an issue accessing them. Here's my code so far (listOrdicRows is the text file of the election read into an ordered list):
public CountyResults(List<OrderedDictionary> listOrdicRows, String raceCode)
{
foreach (OrderedDictionary row in listOrdicRows)
{
bool duplicate = false;
foreach (County indivCounty in CountyList)
{
if (indivCounty.countyName == row["county_name"].ToString() && raceCode == row["race_code"].ToString())
{
duplicate = true;
break;
}
}
if (!duplicate && raceCode == row["race_code"].ToString())
{
CountyList.Add(new County(row["county_code"].ToString(), row["county_name"].ToString(), row["precincts"].ToString(), row["precincts_reporting"].ToString()));
}
}
populateCountyDict(listOrdicRows);
}
public void populateCountyDict(List<OrderedDictionary> listOrdicRows) //Dynamically populates County Dictionary
{
foreach (County x in CountyList)
{
String CountyName = x.countyName;
List<OrderedDictionary> candidatesWithVotes = null;
foreach (OrderedDictionary row in listOrdicRows)
{
if (CountyName == row["county_name"].ToString())
{
OrderedDictionary tempDictionary = new OrderedDictionary();
tempDictionary.Add(row["candidate_name"], row["total_votes"]);
candidatesWithVotes.Add(tempDictionary);
}
}
countyDict.Add(CountyName, candidatesWithVotes);
}
}
Any help would be appreciated, as I'm exceedingly stuck. Someone asked for what the file looks like, and here's a few lines
ElectionDate | PartyCode | PartyName | RaceCode | OfficeDesc | CountyCode | CountyName | Juris1num | Juris2num | Precincts | PrecinctsReporting | CanNameLast | CanNameFirst | CanNameMiddle | CanVotes
------------ | --------- | ---------- | -------- | ---------------------------- | ---------- | ---------- | --------- | --------- | --------- | ------------------ | ----------- | ------------ | ------------- | --------
2020/08/18 | REP | Republican | USR | United States Representative | ESC | Escambia | 001 | | 0 | 0 | Gaetz | Matt | | 29272
2020/08/18 | REP | Republican | USR | United States Representative | HOL | Holmes | 001 | | 6 | 6 | Gaetz | Matt | | 2131
2020/08/18 | REP | Republican | USR | United States Representative | OKA | Okaloosa | 001 | | 52 | 52 | Gaetz | Matt | | 25861
Linq can make it a bit easy and readable.
I have created a sample file to just few columns
Next is code
public class ElectionInfo
{
public string Race { get; set; }
public string County { get; set; }
public string FName { get; set; }
public int VoteCnt { get; set; }
}
static void Main(string[] args)
{
Dictionary<string, List<ElectionInfo>> dict1 = File.ReadAllLines(#"C:\x1\TextFile2.txt")
.Select(record => record.Split(','))
.Select(cell => new ElectionInfo() { Race = cell[0], County = cell[1], FName = cell[2], VoteCnt = int.Parse(cell[3]) })
.GroupBy(x => x.Race)
.ToDictionary(t => t.Key, t => t.ToList<ElectionInfo>())
;
I have a collection like this:
Order //Collection
|-OrderId
|-DateOfOrder
|-PartyName
|-OrderDetails //Collection
| |-ItemName
| |-Quantity
| |-Rate
| |-Amount
|-Dispatch //Collection
| |-InvoiceNo
| |-DateOfDispatch
| |-DispatchDetails //Collection
| | |-ItemName
| | |-Quantity
| | |-Rate
| | |-Amount
Now I want to flatten this collection, so that I can show data in below mentioned pattern:
OrderId | DateOfOrder | PartyName | InvoiceNo | DateOfDispatch | Dispatch ItemName | Dispatch Quantity | Dispatch Rate | Dispatch Amount
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
I have tried:
Orders = new ObservableCollection<Order>(orderService.GetAllOrders()
.SelectMany(x => x.Dispatches)
.SelectMany(x => x.DispatchDetails)
.ToList()
);
The relation between OrderDetails and DispatchDetails is not clear to me, and DispatchItemTransactions seems to be missing from your data structure. Anyway, I hope you find this simple approach useful:
foreach(var order in Orders)
foreach(var dispatch in order.Dispatches)
foreach(var dispatchDetail in dispatch.DispatchDetails)
{
// now construct your record object from order.OrderId, order.DateOfOrder, ... , dispatchDetail.Amount
}
For this to work you'll need to construct new Order and Dispatch objects. Also query syntax will make this much easier to read.
Orders = new ObservableCollection<Order>(
from o in orderService.GetAllOrders
from d in o.Dispatches
from dd in d.DispathDetails
select new Order
{
OrderId = o.OrderId,
DateOfOrder = o.DateOfOrder,
PartyName = o.PartyName,
Dispatches = new List<Dispatch>
{
new Dispatch
{
InvoiceNo = d.InvoiceNo
DateOfDispatch = d.DateOfDispatch
DispatchDetails = new List<DispatchDetail> { dd }
}
}
});
Though instead of a collection of Order you might want to just use an anonymous class instead
from o in orderService.GetAllOrders
from d in o.Dispatches
from dd in d.DispathDetails
select new
{
OrderId = o.OrderId,
DateOfOrder = o.DateOfOrder,
PartyName = o.PartyName,
InvoiceNo = d.InvoiceNo
DateOfDispatch = d.DateOfDispatch,
DispatchItemName = dd.ItemName,
DispatchQuantity = dd.Quantity,
DispatchRate = dd.Rate,
DispatchAmount = dd.Amount
}
I have DataTable Like this
Thank you Bob Vale for your help
what is (Select(X,i) mean in your linq,
but as i made a mistake in my table
I have this
No | Size | Type | FB | FP
----------------------------------------
100 | 2 | typeA | FB1 | A1
101 | 3 | typeB | FB1 | A1
101 | 4 | typec | FB1 | A1
103 | 4 | typeC | FB2 | A2
103 | 5 | typeD | FB2 | A2
103 | 6 | typeE | FB2 | A2
I want to have some thing like that
No | Size | Type | FB | FP
---------------------------------
100 | 2 | typeA | FB1 | A1
101 | 3 | typeB | FB1 | A1
| 4 | typec | |
103 | 4 | typeC | FB2 | A2
| 5 | typeD | |
| 6 | typeE | |
How can I make it? I can make Group By
var result = from row in cableDataTable.AsEnumerable()
group row by new
{
FB = row.Field<string>("FB"),
FP = row.Field<string>("FP"),
Size = row.Field<int>("Size"),
Type = row.Field<int>("Type"),
no= row.Field<int>("no"),
} into g
select new
{
FB = g.Key.FB,
FP = g.Key.FP,
Size = g.Key.Size,
Type = g.Key.Type
no= g.Key.no
};
but it that could't give the result
thank you for your attention
How about this:
// First declare a conversion from the DataTable to an anon type
var rows = cableDataTable.AsEnumerable()
.Select(x => new {
Size = x.Field<int>("Size"),
Type= x.Field<string>("Type"),
FB = x.Field<string>("FB"),
FP = x.Field<string>("FP")
});
// Now use group by, ordering and select many to select the rows
var result = rows.GroupBy (row => new {row.FB, row.FP} )
.OrderBy (g => g.Key.FB)
.ThenBy(g => g.Key.FP)
.SelectMany(g => g.OrderBy(row => row.Size)
.Select((x,i) =>
new {
Size = x.Size,
Type = x.Type,
FB = (i==0) ? x.FB : null,
FP= (i==0) ? x.FP : null
}));
You can use linq query as
var result = cableDataTable.AsEnumerable().GroupBy(g => new { g.FB, g.FP}).Select(x => x);
I have a list with complex data
public class CAR
{
public int ID {get ; set ; }
public string Name { get ; set ; }
public string EngineType { get ; set ; }
public List<string> Months { get; set; }
}
Note that Months data is List<string> its max count is 150
List<CAR> A = new List<CAR>();
List<CAR> B = new List<CAR>();
A has follwoing data
ID | Name | EngineType | Months[0] | Months[1] | Months[2] | Months[3] .. | Months[149] |
1 | Zen | 1001 | 1 | 1 | 4 | 5 .. | 6 |
2 | Benz | 2002 | 6 | 4 | 5 | 6 .. | 2 |
3 | Zen | 1001 | 3 | 1 | 7 | 5 .. | 0 |
4 | Zen | 1001 | 2 | 2 | 4 | 5 .. | 6 |
5 | Zen | 2002 | 2 | 2 | 4 | 5 .. | 6 |
6 | Benz | 2002 | 1 | 1 | 1 | 1 .. | 1 |
IF EngineType and Name are same we add those rows and store the result in a single row
Eg : adding rows
row 1 in B = 1 + 3 + 4
row 2 in B = 2 + 6
row 3 in B = 5
B should contain the following op
ID | Name | EngineType | Months[0] | Months[1] | Months[2] | Months[3] ... | Months[149] |
- | Zen | Petrol | 6 | 4 | 15 | 15 .. | 12 |
- | Benz | Diesel | 7 | 5 | 6 | 7 | 3 |
- | Zen | Diesel | 2 | 2 | 4 | 5 .. | 6 |
had months data been separate entity of type integer something else i could have done this
B = from val in A
group val by new val.EngineType into g
select new CAR{
EngineType = g.Key,
Name = g.Name,
Month0 = g.Sum(p => p.Month0),
Month1 = g.Sum(p => p.Month1),
Month2 = g.Sum(p => p.Month2),
.
.
.
.
.
.
Month148 = g.Sum(p => p.Month148),
Month149 = g.Sum(p => p.Month149)
}.ToList<CAR>();
But since its of type List<string> is there a way to get this done?
Thanks a lot!
Use the power of LINQ:
var B = A.GroupBy(x => new { x.Name, x.EngineType })
.Select(g => new Car
{
Name = g.Key.Name,
EngineType = g.Key.EngineType,
Months = g.SelectMany(x => x.Months.Select((y,i) => new { i, y = int.Parse(y) }))
.GroupBy(x => x.i)
.OrderBy(g2 => g2.Key)
.Select(g2 => g2.Sum(x => x.y).ToString()).ToList()
}).ToList();
foreach (CAR c in A)
{
bool blnadded = false;
if (B.Count == 0)
{
B.Add(c);
blnadded = true;
}
else
foreach (CAR d in B)
{
if (d.Name == c.Name && d.EngineType == c.EngineType)
{
for (int i = 0; i < d.Months.Count; i++)
d.Months[i] = (Convert.ToInt32(d.Months[i]) + Convert.ToInt32(c.Months[i])).ToString();
blnadded = true;
}
}
if (blnadded==false)
B.Add(c);
}
I have an class which contains the following properties:
public class SomeClass()
{
public Int32 ObjectId1 {get;set;}
public Int32 ObjectId2 {get;set;}
public Int32 ActiveThickeness {get;set;}
public Int32 ActiveFilterThickness {get;set;}
}
I also have 2 lists:
List<SomeClass> A
List<SomeClass> B
List A has data:
| ObjectId1 | ObjectId2 | ActiveThickness | ActiveFilterThickness |
-------------------------------------------------------------------
| 1 | 3 | 50 | 0 |
------------------------------------------------------------------
| 1 | 2 | 400 | 0 |
-------------------------------------------------------------------
| 4 | 603 | 27 | 0 |
-------------------------------------------------------------------
List B has data:
| ObjectId1 | ObjectId2 | ActiveThickness | ActiveFilterThickness |
-------------------------------------------------------------------
| 1 | 3 | 0 | 13671 |
------------------------------------------------------------------
| 1 | 2 | 0 | 572 |
-------------------------------------------------------------------
| 29 | 11 | 0 | 4283 |
-------------------------------------------------------------------
I want to merge A and B (using LINQ if possible) into List C of SomeCalss which contains data as followed:
| ObjectId1 | ObjectId2 | ActiveThickness | ActiveFilterThickness |
-------------------------------------------------------------------
| 1 | 3 | 50 | 13671 |
------------------------------------------------------------------
| 1 | 2 | 400 | 572 |
-------------------------------------------------------------------
| 29 | 11 | 0 | 4283 |
-------------------------------------------------------------------
| 4 | 603 | 27 | 0 |
-------------------------------------------------------------------
How can I achieve that?
Use GroupBy to group common objects and Sum to sum required properties
var ab = A.Concat(B).GroupBy(x => new
{
x.ObjectId1,
x.ObjectId2
});
var result = ab.Select(x => new SomeClass
{
ObjectId1 = x.Key.ObjectId1,
ObjectId2 = x.Key.ObjectId2,
ActiveFilterThickness = x.Sum(i => i.ActiveFilterThickness),
ActiveThickeness = x.Sum(i => i.ActiveThickeness)
});
See LINQ - Full Outer Join (SO).
By doing a left outer join and a right outer join, and then taking the union of those two, you should get what you're looking for.
var leftOuterJoin = from someclass1 in A
join someclass2 in B
on someclass1.ObjectID2 equals someclass2.ObjectID2
into temp
from item in temp.DefaultIfEmpty(new SomeClass(){ objectID1 = someclass1.objectID1, ... })
select new SomeClass()
{
...
};
var rightOuterJoin = from someclass2 in B
join someclass1 in A
on someclass1.ObjectID2 equals someclass2.ObjectID2
into temp
from item in temp.DefaultIfEmpty(new SomeClass(){ objectID1 = someclass1.objectID1, ... })
select new SomeClass()
{
...
};
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);