i have a list of objects
public int id { get; set; }
public string device_code { get; set; }
public string device_type { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
while returning the list i want to remove "device_code" and "device_type" from the list and return the list only with "id","authentication_token" and "status".
How can I delete certain objects?
You must cast your object to another type that will contain only needed properties.
You can do this easy with linq:
var result = yourCollection.Select(x => new YourTempClass(){property1=x.property1});
You seem to not want to remove objects, but properties of the objects.
public class ClassWithAllProperties
{
public int id { get; set; }
public string device_code { get; set; }
public string device_type { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
}
var allInstances = new List<ClassWithAllProperties>();
// populate list
var allInstancesButNotAllProperties = allInstances.Select(x => new { id = x.id, authentication_token = x.authentication_token, Status = x.Status }).ToList();
Now this list contains only the properties you want. However it obviously also does not contain instances of ClassWithAllProperties. It contains so-called anonymous classes. Classes the compiler builds in the background for you, based on your description in the new.
It's simple, create another class containing properties that are required and then return its object using the list you have created.
Original Class
public class Data {
public int id { get; set; }
public string device_code { get; set; }
public string device_type { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
}
Class That will be returned
public class DataTobeReturned {
public int id { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
}
Suppose you have list like
List<Data> list = // some data;
You can do
List<DataTobeReturned> list2 = list.Select(x => new DataTobeReturned { x.id, x.Status, x.authentication_token}).ToList();
Simply return the list2 object.
If you have this class:
class MyClass
{
public int id { get; set; }
public string device_code { get; set; }
public string device_type { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
}
...and you have a list of them...
List<MyClass> list;
You can extract just the properties you want into an anonymous type by using LINQ:
var justWhatIWant = list.Select( a => new
{
id = a.id,
authentication_token = a.authentication_token,
Status = a.Status
});
The anonymous type isn't interface-compatible with anything, but you could use it to, say, create some JSON.
Related
I want to Read Related Data but only read the specific field.
if use include theninclude will read all fiedl.
so I use .Select, but how to use .Select to achieve .ThenInclude?
Thanks~
var ViewModel = await _context.A_Table
.Select(s => new ViewModel {
A_TableId = s.Id,
B_Table = s.B_Table,
C_Table = ??? (s.B_Table.C_Table is wrong)
});
public class A_Table
{
public int Id { get; set; }
public string Field1 { get; set; }
public IList<B_Table> B_Table { get; set; }
}
public class B_Table
{
public int Id { get; set; }
public string Field1 { get; set; }
public int A_TableId { get; set; }
public int C_TableId { get; set; }
public C_Table C_Table { get; set; }
}
public class C_Table
{
public int Id { get; set; }
public string Field1 { get; set; }
public B_Table B_Table { get; set; }
}
this is because B_Table property is list of B_Table so when you want to access C_Table property inside it you have to specify which item in the list you want to access
e.g. s.B_Table[0].C_Table to access first item in the list.
if you want aggregate all items in side the list you can use SelectMany using Linq inside namespace System.Linq
e.g. s.B_Table.SelectMany(B_Table => B_Table.C_Table).ToList()
Imagine I have classes like:
// DTO
public class RequestrDto
{
public string Name { get; set; }
public ICollection<int> CityIds { get; set; }
}
// ENTITY
// PLACE
public class Place
{
public int Id { get; set; }
public string Name { get; set; }
public List<City> Cities { get; set; }
}
// CITY
public class City
{
public int Id { get; set; }
public int? PlaceId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public List<City> Cities { get; set; }
public Place Place { get; set; }
}
I'd like to check if cities exist in the database and add to the newly created entity class which will be added to the DB.
So, I can do like:
var placeEntity = new Place()
{
Name = RequestrDto.Name;
}
var cities = _context.Cities.Where(x => request.CityIds.Contains(x.Id)).ToList();
placeEntity.Cities.AddRange(cities);
How can I get Cities and check if they are in the DB? I know I can iterate over it by foreach but I'm looking for a fancy way.
You can use Except
Produces the set difference of two sequences.
var cities = _context.Cities.Where(x => request.CityIds.Contains(x.Id))
.ToList();
var ids = cities.Select(x => x.Id);
var missing = request.CityIds.Except(ids);
// or
var missing = request.CityIds.Except(cities.Select(x => x.Id));
I need to pull a specific value from a nested object without using a foreach loop. I think the right approach here is a linq query, but I'm unable to grab the value I need. Considering the class structure:
public class Order
{
public int OrderID { get; set; }
public List<OrderItems> { get; set; }
}
public class OrderItems
{
public int OrderItemID { get; set; }
public string ItemName { get; set; }
public int Quantity { get; set; }
public List<OrderItemShipping> OrderItemShippings { get; set; }
}
public class OrderItemShipping
{
public int OrderItemShippingID { get; set; }
public Address ShipAddress { get; set; }
public class Address
{
public int AddressID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
}
I want to be able to do something like:
var shipToAddress = Order.OrderItems.OrderItemShipping.FirstOrDefault(x => x.Address.Address1);
But my syntax must not be correct, because I'm unable to grab the value I need?
If you need to access items of (nested) collections SelectMany is your friend:
var shipToAddress = Order.OrderItems
.SelectMany(oi => oi.OrderItemShipping.Select(ois => ois.ShipAddress.Address1)))
.FirstOrDefault();
Your syntax was wrong because the overload of FirstOrDefault expects a predicate(so a function that returns a bool) but you were passing: FirstOrDefault(x => x.Address.Address1).
If you need to filter it somehow("specific value from a nested object") you need to explain your requirement more precisely.
I have a class defined as:
public class ReportObjectInformation
{
public string tableName { get; set; }
public int progressBarValue { get; set; }
public int rowCount { get; set; }
public bool canConnect { get; set; }
public int index { get; set; }
public string summaryFile { get; set; }
public string reportFile { get; set; }
public string errorFile { get; set; }
}
I currently have seven different lists of objects in my code. Is there a way I can do something like:
public class ReportObjectInformation
{
public string tableName { get; set; }
public int progressBarValue { get; set; }
public int rowCount { get; set; }
public bool canConnect { get; set; }
public int index { get; set; }
public string summaryFile { get; set; }
public string reportFile { get; set; }
public string errorFile { get; set; }
public List<> listOne { get; set; } // add this
public List<> listTwo { get; set; } // add this
}
And then in my code set the list to be one of my seven predefined types of lists?
One of my other lists is made up of this class:
class parameters
{
public string firstName{ get; set; }
public string lastName{ get; set; }
public string address{ get; set; }
public string city{ get; set; }
public string state { get; set; }
public string country{ get; set; }
public string active_flag { get; set; }
}
which I create in my code as:
List<parameters> parm_list = new List<parameters>();
The parm_list is populated with data. Now I want to add that list to this other object I'm creating. At other times in my code I'll want to set the list to one of the my other types but for now how would I do this? Is this even possible?
ReportObjectInformation reportObject = new ReportObjectInformation();
reportObject.tableName = "UserInformation";
reportObject.listOne = parm_list;
reportObject.listTwo = someother_list;
If you can guarantee that a particular instance of ReportObjectInformation will work with a given type of List you can do this:
public class ReportObjectInformation<TOne, TTwo>
{
public string tableName { get; set; }
public int progressBarValue { get; set; }
public int rowCount { get; set; }
public bool canConnect { get; set; }
public int index { get; set; }
public string summaryFile { get; set; }
public string reportFile { get; set; }
public string errorFile { get; set; }
public List<TOne> listOne { get; set; }
public List<TTwo> listTwo { get; set; }
}
Which lets you specify which types you want the ReportObjectInformation object lists to use.
You could make ReportObjectInformation generic
public class ReportObjectInformation<TOne, TTwo>
{
public List<TOne> listOne { get; set; } // add this
public List<TTwo> listTwo { get; set; } // add this
}
Then create an instance like this
var reportInfo = new ReportObjectInformation<parameters, otherClass>();
reportInfo.listOne = new List<parameters>();
reportInfo.listTwo = new List<otherClass>();
Of course this means that each instance can not switch to hold a list of one of the other types.
Well, since you want to assign of lists of different types to the object during runtime, you'll be left with no type checking. Can be implemented like:
public class ContainingClass
{
public IList SomeList { get; set; }
}
then you can do
var c = new ContainingClass();
c.SomeList = new List<int> { 1, 2, 3 };
c.SomeList = new List<string> { "abc", "def" };
foreach (var member in c.SomeList)
Console.WriteLine(member);
But you should only do this as a last resort, generally prefer using generics or clean design, because this is:
Slow - you'll have to cast a lot since IList works with object
Unsafe - who knows what list is there at a given time? Not to mention you'll be left without compile-time type checks (those are very powerful to have, try not to lose them).
Generally consider this a no-go unless you really really really have no choice (e.g. legacy code compatibility).
I've been trying to find an answer to this on google and on SO
but everywhere I have found uses anonymously typed result lists
what I am trying to acheive is to take a List<SecondaryStandard>
and create a grouped List of SecondaryStandard
each SecondaryStandard looks like this
public class SecondaryStandard
{
public string Id { get; set; }
public int IdNumeric { get; set; }
public string IdText { get; set; }
public Sample Sample { get; set; }
public string StandardName { get; set; }
public DateTime DateCompleted { get; set; }
public SamplePoint SamplingPoint{ get; set; }
public Instrument Instrument{ get; set; }
public string ContainerId { get; set; }
public double Value { get; set; }
public string ComponentName { get; set; }
public string PointLocation { get; set; }
public string Description { get; set; }
public string Description2 { get; set; }
public string Analysis { get; set; }
public string Units { get; set; }
}
what i want is a List() where the Value Property is an average of results for each ComponentName.
Any ideas on how I could achieve this in a strongly typed way or do I need to suck it up and use anonymous objects to achieve what I'm looking for?
You mean this?
List<SecondaryStandard> list = new List<SecondaryStandard>();
// populate list
List<SecondaryStandard> result = list
.GroupBy(l => l.ComponentName)
.Select(s => new SecondaryStandard() { ComponentName = s.Key, Value = s.Average(x => x.Value) }).ToList();