I have two DTO classes in a C# MVC web app and I need to return a list generated from one class with a list of data generated by the second within the first list. (Think nested array eg [0[a,b], 1[a,b,c], 2[a,b,c,d], 3,[a], etc...])
This is for an internal application where staff members educate others about their job roles.
The following is what I have so far
//Abstract code representative of end goal
var foo = from x in _fooCtx.Foo
where (x.Condition1 && x.Condition2 && x.Condition3 && x.Condition4 > 0)
select new Models.ResourceDTO()
{
FirstName = x.FirstName,
LastName = x.LastName,
ResourceID = x.ResourceID,
};
//currently loops through each memeber of staff in list above and grabs their wamits history.
foreach (var foobar in foo)
{
int foobarID = foo.ResourceID;
var bar = from u in _barCtx.BarViews
where (u.PupilID == foobarID || u.TeacherID == foobarID)
select new Models.ApplicationDTO()
{
pupilName = u.Pupil,
teacherName = u.Teacher,
appDate = u.appDate.ToString(),
appID = u.ID,
};
var leaderList = bar.ToList();
}
The above works fine in getting a list of active staff members and then looping through any previous sessions they may have done. I need to return the staff list where each member has the list generated by the second DTO select in the foreach loop. So a list of foo data and within this a list of bar data. If this makes sense.
Create a custom DTO
Public class test
{
// add required properties along with list of ApplicationDTO
// so it will be something like this (getter setters)
FirstName
LastName
ResourceID
List<ApplicationDTO>
}
then you can create a list of this test class and use it
P.S : this is just a sample example to help you understand how you can achieve this
You can use Union for appending two dtos with the same type.
This will merge two dtos together:
Dto1.Union(Dto2);
Related
Today I've faced one very strange behavior. After creating an object with Linq query and object initializer with setting property of List<string> type the original collection and the collection that the object contains have different entries order.
public class PrintHeaderModel
{
public List<string> Ships { get; set; }
}
...
var shipsList = new List<string>() { /* some items */ };
var model = (from inv in db.invoices
where inv.ListID == id && inv.RealmID == realmId
select new PrintHeaderModel()
{
Ships = shipsList,
}).FirstOrDefault();
After that the orders of entries in model.Ships and shipsList are different
Notes:
db is DbContext instance (I'm using Entity Framework and MySQL database)
shipsList is not sorted after it's filled
If I create model object without Linq (just with "new"), the order of entries is the same in model and in the list
The order becames correct if I reassign model.Ships right after model is created:
model.Ships = shipsList; // after that the order of entries is correct
The order of entries in model.Ships is not the same always. It changes randomly without any changes in code or database
Where was I wrong?
I am fairly new to C#
I am trying to retrieve some information from an external data source and store it in array, once it is in an array I wish to sort it by time.
I know how to do this for just one column in a row, however the information I require has multiple columns.
For example:
foreach (Appointment Appoint in fapts)
{
// Store Appoint.Subject, Appoint.Start, Appoint.Organiser.Name.ToString(), Appoint.Location in an array
}
// Sort my array by Appoint.Start
foreach ( item in myNewArray )
{
//print out Appoint.Subject - Appoint.Start, Appoint.Organiser.Name.ToString() and Appoint.location
}
Many thanks for your help.
EDIT:
I have multiple data sources which pull in this:
foreach (Appointment Appoint in fapts)
{
// Store Appoint.Subject, Appoint.Start, Appoint.Organiser.Name.ToString(), Appoint.Location in an array
}
Hence the need to sort the items in a new array, I know this isn't very efficent but there is no way of getting the information I need in any other way.
You can sort a list using the LINQ sorting operators OrderBy and ThenBy, as shown below.
using System.Linq;
and then...
var appointments = new List<Appointment>();
var sortedAppointments = list.OrderBy(l => l.Subject).ThenBy(l => l.Name).ToList();
This will create a new list of appointments, sorted by subject and then by name.
It's unclear what your final aim is but:
Use a generic List instead of an array:
See this SO question for more information as to why using a List is prefered.
List<Appointment> appointments = new List<Appointment>();
foreach (Appointment Appoint in fapts)
{
appointments.Add(Appoint);
}
foreach (var item in appointments)
{
Console.WriteLine(item.Subject);
Console.WriteLine(item.Foo);
// Here you could override ToString() on Appointment to print eveything in one Console.WriteLine
}
If the aim of your code is to order by time, try the following:
var sortedAppointments = fapts.OrderBy(a => a.Start); // assuming Start is a DateTime property of `Appointment`.
Consider a Dictionary Object instead of an array if the data is conceptually one row multiple columns.
foreach(KeyValuePair<string, string> entry in MyDic)
{
// do something with entry.Value or entry.Key
}
You already have a list of objects in fpts, sort that list itself:
fpts.OrderBy(x => x.Subject).ThenBy(x => x.Location).ToList();
LINQ is your friend here.
fapts appears to already be a collection so you could just operate on it.
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start).ToArray()
I've used the ToArray() call to force immediate evaluation and means that myNewArray is already sorted so that if you use it more than once you don't have to re-evaluate the sort.
Alternatively if you are only using this once you can just as easily miss the ToArray() portion out and then execution of the sort will be deferred until you try and enumerate through myNewArray.
This solution puts the source objects into the array, but if you are just wanting to store the specific fields you mention then you will need to use a select. You have two choices for the array item type, you can either use an anonymous class which provides difficulties if you are returning this array from a function or define a class.
For anonymous:
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start)
.Select(Appoint => new {
Start = Appoint.Start,
Organiser = Appoint.Organiser.Name.ToString(),
Location = Appoint.Location
}).ToArray();
For named class assuming class is MyClass:
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start)
.Select(Appoint => new MyClass {
Start = Appoint.Start,
Organiser = Appoint.Organiser.Name.ToString(),
Location = Appoint.Location
}).ToArray();
You have a wide range of options. The 2 most common are:
1) Create a class, then define an array or list of that class, and populate that
2) Create a structure that matches the data format and create an array or list of that
Of course, you could put the data into an XML format or dataset, but that's probably more work than you need.
public List<foo> appointments = new List<foo>();
public struct foo
{
public string subject ;
public DateTime start ;
public string name ;
public string location ;
}
public void foo1()
{
// parse the file
while (!File.eof())
{
// Read the next line...
var myRecord = new foo() ;
myRecord.subject = data.subject ;
myRecord.start = data.Start ;
myRecord.name = data.Name ;
//...
appointments.Add(myRecord);
}
}
Enjoy
(Since I can't comment and reply to the comment - it wasn't clear if he had a class, etc. or was just showing us what he wanted to do. I assumed it was just for demonstration purposes since there wasn't any info as to how the data was being read. If he could already put it into a class, than the first answer applied anyway. I just tossed the last 2 in there because they were options for getting the data first.)
I'm working with ASP.net Web Service C#.net3.5 and using the LINQ TO SQL to manipulate with SQL DataBase
and I want to return all the countries information from Countries Table,
so I wrote a web method that return a List of object, each object have two data field Country_Id, Country_Name and here is the method :
public List<CountryObject> ReturnAllCountries()
{
ProjectTwoDataBaseDataContext DataBase = new ProjectTwoDataBaseDataContext();
var Country = from a in DataBase.Countries
select new {a.Country_Id,a.Country_Name };
CountryObject TempObject = new CountryObject();
List<CountryObject> TempList = new List<CountryObject>();
foreach (var a in Country)
{
TempObject.setCountry_Id(a.Country_Id);
TempObject.setCountry_Name(a.Country_Name);
TempList.Add(TempObject);
}
return TempList;
}
but when I run the code I get a List that contains the same Object, and this object have the values that get from the last round of Foreach.
I try the Following :
public List<CountryObject> ReturnAllCountries()
{
ProjectTwoDataBaseDataContext DataBase = new ProjectTwoDataBaseDataContext();
var Country = from a in DataBase.Countries
select new {a.Country_Id,a.Country_Name };
CountryObject TempObject;
List<CountryObject> TempList = new List<CountryObject>();
foreach (var a in Country)
{
TempObject = new CountryObject();
TempObject.setCountry_Id(a.Country_Id);
TempObject.setCountry_Name(a.Country_Name);
TempList.Add(TempObject);
}
return TempList;
}
and I get what I want >> WHy ????
The two loops do very different things:
In the first example, you're only creating one object/ Then every time through the loop, modifying the same object, then re-adding it to the list. So your list contains a bunch of references to the same object, over and over again.
This happens because CountryObject, like all classes is a reference type. When you add the instance to TempList you are only adding a reference to that instance, not a copy of it, so when you later modify the instance, those changes will be reflected in the list because it only has a reference to the same instance.
In the second example, creating a new object on every iteration and adding that newly created object to the loop.
Because you're creating a new instance every time, the instances which the list references are not getting modified.
Further Reading
Value Types and Reference Types
Your first code snippet only creates one object that you put into the list multiple times. The second creates one per iteration of the foreach loop.
On another note I would suggest changing CountryObject to have Id and Name properties and you won't need to use an anonymous class in the Linq query. Properties are preferable over get and set methods.
public class CountryObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public List<CountryObject> ReturnAllCountries()
{
ProjectTwoDataBaseDataContext DataBase = new ProjectTwoDataBaseDataContext();
var Country = from a in DataBase.Countries
select new CountryObject{Id=a.Country_Id, Name=a.Country_Name };
return Coutry.ToList();
}
I've looked into various different ways of array's, arraylist's, dictionaries... but as I'm used to PHP I'm not entirely sure on the best way I could collect the following information.
My program loops through each user, and if their is a location ID, I want to add that to some sort of collection / array. It's expected that different users will have the same location ID.
If the location ID is the same, I need to increase an integer of how many occurrence for that location ID.
Example:
User1 - Location1
User2 - Location3
User3 - Location3
Location1 = 1
Location3 = 2
Also I need to somehow append each user ID to this collection. So Location3 / 2 occurrences / user2/user3
I've been trying to figure out the best way of doing this for about two hours now, and all the different methods of multidimensional arrays, arraylists, dictionaries is all a little confusing as it all seems abstract to my PHP knowledge. I think C# handles arrays in an entirely different way.
Essentially, the collection with unique location ID's / occurrences / and users collection needs to be stored in something that can be passed to somewhere else in my program as an argument.
I've made a PHP script which does exactly what I'm after
foreach($call["data"] as $v)
{
// Foreach USER ($v containing their unique ID and location ID.)
$user_id = $v["id"];
$location_id = $v["location"]["id"];
// This adds the location ID as the key within the array, followed by every user who has it. I don't need a count in this case, as I could just count the number of users.
$collection[$location_id][$user_id] = null;
}
This in return creates this array when printed using print_r
[106078429431815] => Array
(
[620790873] =>
[626276302] =>
[100000152470577] =>
)
(Small part of the output). - Added PHP Example.
Anyone know how I can get C# to collect the same information in the same way my PHP array does?
using System.Linq;
var grouppingByLocation = users.GroupBy(u => u.LocationID);
foreach (var g in grouppingByLocation)
{
Console.WriteLine("Location id: {0}", g.Key);
foreach (var u in g)
{
Console.WriteLine("User id: {0}", u.ID);
}
}
See Enumerable.GroupBy() for more details.
This is an Extension Method over IEnumerable<T> interface implemented by any built-in collection (such as Array T[], List<T>, Dictionary<K,V>, etc.) which accepts a lambda expression pointing to a property of class collection of which you're grouping by.
If you want to build the list looping through initial data, you can create object like this:
var list = new Dictionary<int, Tuple<int, List<int>>();
And fill it in the loop
if(list[locationID]==null) list[locationID] = Tuple.Create(0,new List<int>());
//..
list[locationId].Item1++; // counter
list[locationId].Item2.Add(userId); //list of users
Create an object to hold each item of data.
public Class Model{
public int LocationId {get;set;}
public int Occurences{get;set;}
public IList<User> Users{get;set;}
}
Initialize the container as a list of items.
var container = List<Model>();
Process you list of users.
foreach(var user in userList){
var model = container.SingleOrDefault(x=> x.LocationId == user.LocationId);
if(model != null){
model.Users.Add(user);
} else{
model = new Model{
model.Users = new List<User>.Add(user);
model.LocationId = user.LocationId;
container.Add(model)
}
model.Occruences ++;
}
}
var byLocation = users.Where(u => !string.IsNullOrEmpty(u.Location))
.GroupBy(u => u.Location);
var stats = byLocation.Select(l => string.Format("{0} / {1} occurrences / {2}",
l.Key, l.Count(), string.Join("/", l.Select(u => u.User)));
// And just to print the result
foreach (var location in stats)
Console.WriteLine(location);
with my Repository classes, I use LinqToSql to retrieve the data from the repository (eg. Sql Server 2008, in my example). I place the result data into a POCO object. Works great :)
Now, if my POCO object has a child property, (which is another POCO object or an IList), i'm trying to figure out a way to populate that data. I'm just not too sure how to do this.
Here's some sample code i have. Please note the last property I'm setting. It compiles, but it's not 'right'. It's not the POCO object instance .. and i'm not sure how to code that last line.
public IQueryable<GameFile> GetGameFiles(bool includeUserIdAccess)
{
return (from q in Database.Files
select new Core.GameFile
{
CheckedOn = q.CheckedOn.Value,
FileName = q.FileName,
GameFileId = q.FileId,
GameType = (Core.GameType)q.GameTypeId,
IsActive = q.IsActive,
LastFilePosition = q.LastFilePosition.Value,
UniqueName = q.UniqueName,
UpdatedOn = q.UpdatedOn.Value,
// Now any children....
// NOTE: I wish to create a POCO object
// that has an int UserId _and_ a string Name.
UserAccess = includeUserIdAccess ?
q.FileUserAccesses.Select(x => x.UserId).ToList() : null
});
}
Notes:
Database.Files => The File table.
Database.FilesUserAccess => the FilesUserAccess table .. which users have access to the GameFiles / Files table.
Update
I've now got a suggestion to extract the children results into their respective POCO classes, but this is what the Visual Studio Debugger is saying the class is :-
Why is it a System.Data.Linq.SqlClient.Implementation.ObjectMaterializer<..>
.Convert<Core.GameFile> and not a List<Core.GameFile> containing the POCO's?
Any suggestions what that is / what I've done wrong?
Update 2:
this is what i've done to extract the children data into their respective poco's..
// Now any children....
UserIdAccess = includeUserIdAccess ?
(from x in q.FileUserAccesses
select x.UserId).ToList() : null,
LogEntries = includeUserIdAccess ?
(from x in q.LogEntries
select new Core.LogEntry
{
ClientGuid = x.ClientGuid,
ClientIpAndPort = x.ClientIpAndPort,
// ... snip other properties
Violation = x.Violation
}).ToList() : null
I think that all you need to do is to put another Linq query in here:
q.FileUserAccesses.Select(x => x.UserId).ToList()
i.e. You want to select data from the FileUserAccess records - which I'm assuming are Linq to SQL classes, so to do this you can have something like:
(from fua in q.FileUserAccesses
select new PocoType
{
UserID = fua.UserID,
Name = fua.User.UserName // Not sure at this point where the name comes from
}).ToList()
That should get you pointed in the right direction at least.
What is the type of UserIdAccess? How is it not 'right'? Are you getting the 'wrong' data? if so have you checked your database directly to make sure the 'right' data is there?