I would like to create list of data in list of data. I believe this can be difficult to explain but I will try explain my problem very clear. I created list of data but in this list some arguments are also list of data. I have to write using this code because this are restriction (Our Factory). If I take data, which are not list of data, everything working correct. Where is problem? If I write list in list I get error. Perhaps you can see there my mistake.
Program is compile.
Problem(I take data from third table using mapping in NHibernate):
DestynationName = (List<dictionaryNewInfoSupportList>x.DictImportantInformationSDestination.Select(n=> new DictionaryNewInfoSupportList { Id = n.Destination.Id, Name = n.Destination.Desciption}).ToList();
DestynationName in Model
public Ilist<dictionaryNewInfoSupportList> DestynationName;
Class:
class dictionaryNewInfoSupportList
{
public string Name {get; set;}
public int Id {get; set;}
}
Important:
public IEnumerable<DictionaryListModel> OnList(DictionayDisplayModel dictionary DisplayModel, int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
var displayModel = (DictionaryNewInfoDisplayModel)dictionaryDisplayModel;
if (displayModel == null)
var list = _dictImportantInformation.GetList().Select(
x=> new DictionaryNewInfoListModel
{
Id = x.Id
Description = x.Description,
IsActiveYN = x.IsActive,
DestynationName = (List<DictionaryNewInfoSupportList>) x.DictImportantInformationXDestination.Select(n => new DictionaryNewInfoSupportList
{ Id = n.Destination.Id, Name = Destination.Description}).To.List()
}
).ToList();
return list;
}
I have got answer (Topic Closed)
var list = _dictImportantInformation.GetList().ToList().Select(
x => new DictionaryNewInfoListModel
{
Id = x.Id,
Description = x.Description,
IsActiveYN = x.IsActive,
DeestynationName = x.DictImportantInformationXDestination.Select(n => new DictionaryNewInfoSupportList
{ Id = n.Destination.Id, Name = n.Destination.Description }).ToList()
}
).ToList();
var list = _dictImportantInformation.GetList().ToList().Select(
x => new DictionaryNewInfoListModel
{
Id = x.Id,
Description = x.Description,
IsActiveYN = x.IsActive,
DeestynationName = x.DictImportantInformationXDestination.Select(n => new DictionaryNewInfoSupportList
{ Id = n.Destination.Id, Name = n.Destination.Description }).ToList()
}
).ToList();
Related
I have a table of WorldEvents. Each WorldEvent has a list of Presentations, that happened in some country, regarding that WorldEvent
public class WorldEvent
{
public int ID { get; set; }
public string Name { get; set; }
public List<Presentation> PresentationList { get; set; }
}
public class Presentation
{
public int ID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
public class WorldEventService
{
public List<WorldEvent> GetWorldEvents()
{
List<WorldEvent> worldEventList = new List<WorldEvent>();
List<Presentation> presentationList = new List<Presentation>();
// Create list of Presentations for WorldEvent_1
presentationList = new List<Presentation>()
{
new Presentation() { ID = 1, Name = "Presentation_1", Country = "Germany",},
new Presentation() { ID = 2, Name = "Presentation_2", Country = "UK",},
new Presentation() { ID = 3, Name = "Presentation_3", Country = "UK",},
};
// Add WorldEvent_1 to the list of WorldEvents
worldEventList.Add(new WorldEvent()
{
ID = 1,
Name = "WorldEvent_1",
PresentationList = presentationList,
});
// Create list of Presentations for WorldEvent_2
presentationList = new List<Presentation>()
{
new Presentation() { ID = 4, Name = "Presentation_4", Country = "USA",},
new Presentation() { ID = 5, Name = "Presentation_5", Country = "UK",},
new Presentation() { ID = 6, Name = "Presentation_6", Country = "Japan",},
};
// Add WorldEvent_2 to the list of WorldEvents
worldEventList.Add(new WorldEvent()
{
ID = 2,
Name = "WorldEvent_2",
PresentationList = presentationList,
});
// Create list of Presentations for WorldEvent_3
presentationList = new List<Presentation>()
{
new Presentation() { ID = 7, Name = "Presentation_7", Country = "France",},
new Presentation() { ID = 8, Name = "Presentation_8", Country = "Germany",},
new Presentation() { ID = 9, Name = "Presentation_9", Country = "Japan",},
};
// Add WorldEvent_3 to the list of WorldEvents
worldEventList.Add(new WorldEvent()
{
ID = 3,
Name = "WorldEvent_3",
PresentationList = presentationList,
});
return worldEventList;
}
}
Now - how can I get a list of WorldEvents, whose Presentations took place in the UK.
And - in the list of my interest, WorldEvents should contain info about those UK Presentations only.
In other word, I need this as result:
WorldEvent_1(Presentation_2, Presentation_3)
WorldEvent_2(Presentation_5)
If I've understood what you want. There are many ways to do this, however you can filter first, then recreate your WorldEvents with the filtered list of Presentation
var country = "UK";
var result = worldEventList.Where(x => x.PresentationList.Any(y => y.Country == country))
.Select(x => new WorldEvent()
{
ID = x.ID,
Name = x.Name,
PresentationList = x.PresentationList
.Where(y => y.Country == country)
.ToList()
}).ToList();
or as noted by Gert Arnold in the comments you could filter after the fact
var result = worldEventList.Select(x => new WorldEvent()
{
ID = x.ID,
Name = x.Name,
PresentationList = x.PresentationList
.Where(y => y.Country == country).ToList()
}).Where(x => x.PresentationList.Any())
.ToList();
Note : Because this is not projecting (selecting) each Presentation, any change you make to a Presentation in the result will be reflected in the original data. If you don't want this, you will need to recreate each Presentation
var worldEvent = new WorldEventService.GetWorldEvents();
var filter = "";//userInput
var filteredResult = worldEvent.Select(r => new WorldEvent
{
PresentationList = r.PresentationList.Where(c => c.Country == filter).ToList(),
ID = r.Id,
Name = r.Name
}).ToList();
public static List<WorldEvent> Filter(string Country, List<WorldEvent> events) {
var evs = from ev in events.Where(x => x.PresentationList.Any(y => y.Country == Country))
let targetPres = from pres in ev.PresentationList
where pres.Country == Country
select pres
select new WorldEvent {
ID = ev.ID,
Name = ev.Name,
PresentationList = targetPres.ToList()
};
return evs.ToList();
}
Not sure if my understanding is correct, I guess there's a one to many relationship between your WorldEvent and Presentation table. So if you'd like to get all the WorldEvents and its related Presentations which take place in UK, by using EntityFramework, you can try this:
worldEventContext
.Include(PresentationContext)
.Select(
w => new
{
w.ID,
w.Name,
PresentationList = w.PresentationContext.Where(p => p.Country == "UK")
})
This may be a bit of a dumb question but I'm new to elastic search and nest.
I have a class
Person
{
public string Id {get; set;}
public string Name {get; set;}
public IList<string> PhoneNumbers {get; set;}
}
And what I want to do is update the Phone number by adding to it.
Right now I'm doing it with 2 queries but I'm wondering if there is a way I could manage it with 1.
// See if the Person already exists
var result = NestClient.Search<Person>(s => s
.Index(_indexName)
.Take(1)
.Query(q => q
.Term(p => p.Name, person.Name)
&& q.Term(p => p.Id, person.Id)));
if (result.ServerError != null)
{
throw result.OriginalException;
}
if (result.Documents.FirstOrDefault() == null)
{
var response = NestClient.Index<Person>(person);
if (response.ServerError != null)
{
throw response.OriginalException;
}
}
else
{
// If it does exist update and overwrite
var savedPerson = result.Documents.First();
IList<string> oldNums = SavedPerson.PhoneNumbers;
IList<string> newNums = newPerson.PhoneNumbers;
var combinedNums = oldNums.Concat(newNums);
newPerson.PhoneNumbers = combinedNums.ToList<string>();
var response = NestClient.Update(DocumentPath<Person>
.Id(newPerson.Id),
u => u.Doc(newPerson).DocAsUpsert(true));
if (response.ServerError != null)
{
throw response.OriginalException;
}
}
Basically I want my upsert to add to the existing list of phone numbers if it exists.
If script is an option you can do this with scripted update.
Option with duplicated items after update in array
var updateResponse = client.Update<Document, DocumentPartial>(DocumentPath<Document>.Id(1), descriptor => descriptor
.Script(#"ctx._source.array += tab;")
.Params(p => p.Add("tab", new[] {4, 5, 3})));
and without
var updateResponse = client.Update<Document, DocumentPartial>(DocumentPath<Document>.Id(1), descriptor => descriptor
.Script(#"ctx._source.array += tab; ctx._source.array.unique();")
.Params(p => p.Add("tab", new[] {4, 5, 3})));
Full example:
public class DocumentPartial
{
public int[] Array { get; set; }
}
public class Document
{
public int Id { get; set; }
public int[] Array { get; set; }
}
var client = new ElasticClient(settings);
client.CreateIndex(indexName, descriptor => descriptor
.Mappings(map => map
.Map<Document>(m => m.AutoMap())));
var items = new List<Document>
{
new Document
{
Id = 1,
Array = new[] {1,2,3}
}
};
var bulkResponse = client.IndexMany(items);
client.Refresh(indexName);
var updateResponse = client.Update<Document, DocumentPartial>(DocumentPath<Document>.Id(1), descriptor => descriptor
.Script(#"ctx._source.array += tab; ctx._source.array.unique();")
.Params(p => p.Add("tab", new[] {4, 5, 3})));
Hope it helps.
I've got a method I've been using against IEnumerable no problem. However I want to start using it against IQueryable as well. However, the way I currently have it wont work as its trying to execute my method against the database.
The situation is as follows. I want a property on the object I'm selecting into to be be null if the value selecting from is null or the Id and Name of the property if it exists. For example:
var foos = FooRepository.All().Select(s => new FooBrief()
{
Id = s.Id,
Customer = SimpleData.To(s.Customer, m => m.Id, m => m.Name)
});
where SimpleData.To looks like:
public class SimpleData
{
public int Id { get; set; }
public string Name { get; set; }
public static SimpleData To<T>(T t, Func<T, int> id, Func<T, string> name) where T : class
{
if (t != null)
{
return new SimpleData { Id = id(t), Name = name(t) };
}
return null;
}
}
Is there someway I can get this behaviour whilst allowing it to execute against the database?
NOTE: Because of reasons elsewhere in my code I cannot use .ToList(). I may be adding additional filtering at a later point
The simplest approach is just to perform the selection outside the database, using AsEnumerable:
var foos = FooRepository.All()
.Select(x => new { Id = x.Id,
CustomerId = x.Customer.Id,
CustomerName = x.Name })
.AsEnumerable()
.Select(s => new FooBrief {
Id = s.Id,
Customer = new SimpleData {
Id = s.CustomerId,
Name = s.CustomerName
}
});
The first Select is just to make sure that the database query only pulls out the required fields. If you really still want to use your SimpleData.To method:
// Outdented to avoid scrolling
var foos = FooRepository.All()
.Select(x => new { Id = x.Id,
CustomerId = x.Customer.Id,
CustomerName = x.Name })
.AsEnumerable()
.Select(s => new FooBrief {
Id = s.Id,
Customer = SimpleData.To(s,
s => s.CustomerId,
s => s.CustomerName)
});
I have an object which has properties ID, brandID, brandName, NumPages, and Type.
i need to show the top 5 brands by numPage size, a brand may have multiple IDs, so I need to group by brand
listing.OrderByDescending(o => o.numPage).GroupBy(o=> o.brandName).Take(5).ToList();
is alone the lines of what im looking for but this is not valid code.
It sounds like a given brand name may have several ID's and that you want the top 5 brand's sorted by numPage. Is that correct
If so try the following
var query = listing
.GroupBy(x => x.brandName)
.OrderByDescending(brands => brands.Sum(x => x.numPage))
.Select(x => x.Key)
.Take(5);
Note: After the GroupBy operation you're now passing around a collection of the brand objects instead of single ones. Hence to order by the numPage we need to sum it for all of the brand objects in the group. The .Select(x => x.Key) will select back out the original brandName on which the group is based
just tried and it works:
public class Listing
{
public int ID { get; set; }
public int BrandID { get; set; }
public string BrandName { get; set; }
public int NumPages { get; set; }
public Type Type { get; set; }
}
Here the filtering
Listing listing1 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing2 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing3 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing4 = new Listing() { NumPages = 3, BrandName = "xxxxx" };
List<Listing> allListings = new List<Listing>() { listing1, listing2, listing3, listing4 };
var result = allListings.OrderByDescending(x => x.NumPages).GroupBy(x => x.BrandName).Take(5);
I have an action method returning a JsonResult in my controller:
public JsonResult GetDetails()
{
var rows = //Linq-To-SQL
//Linq-To-Entities
var lifts = (from r in rows
group r by new { r.LiftID, r.LiftDate } into g
select new
{
ID = g.Key.LiftID,
Date = g.Key.LiftDate.ToShortDateString(),
Driver = g.Where(x => x.IsDriver)
.Select(x => x.p).Single().Name,
Passengers = g.Where(x => !x.IsDriver)
.Select(x => x.p.Name)
.Aggregate((x, y) => x + ", " + y)
}).ToList();
return Json(lifts);
}
I use the result in a jQuery script to write out a table.
The data looks like:
ID | Date | Driver | Passengers
1 | 20/06/2010 | David Neale | John Smith, Paul Jones
etc...
I would like the names to be hyperlinks to the route Person\{id} I.e. David Neale. The p property corresponds to a Person object containing both Name and ID.
I don't want to construct the URL manually. How would I construct the object to contain the names as hyperlinks using the MVC routing engine?
It's fairly easy.
Just use Url.Action("actionName", "controllerName", params)
It will create a string using the routing engine, so if you change the routes your code will keep workin just fine
First, I think you have a mistake in your model or in your Linq-To-SQL or Linq-To-Entities querys. Because you don't have an ID for your Persons (Drivers and Passagers), and you will definitly need it if you want a link with an Id of the Person. I think you need to split your Lifts from your Persons and have 2 separate entities (linked by its Id of course).
Second, you need to pass the ID of the Persons from the Controller to the View.
class Lift
{
public int LiftID { get; set; }
public DateTime LiftDate { get; set; }
public IEnumerable<Person> p { get; set; }
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsDriver { get; set; }
}
public JsonResult GetDetails()
{
var rows = new Lift[] { //Linq-To-SQL and Linq-To-Entities replaced by an example
new Lift{LiftID = 1, LiftDate= DateTime.Now, p = new Person[] {
new Person{IsDriver = true, Id = 1, Name = "David Neale"},
new Person{IsDriver = false, Id = 2, Name = "John Smith"},
new Person{IsDriver = false, Id = 3, Name = "Paul Jones"}
}},
new Lift{LiftID = 2, LiftDate= DateTime.Now, p = p = new Person[] {
new Person{IsDriver = true, Id = 4, Name = "Daniel Faraday"},
new Person{IsDriver = false, Id = 2, Name = "John Smith"}
}}
};
var lifts = (from r in rows
select new
{
ID = r.LiftID,
Date = r.LiftDate.ToShortDateString(),
Driver = r.p.Where(x => x.IsDriver)
.Select(x => x.Name).Single(),
Passengers = r.p.Where(x => !x.IsDriver)
.Select(x => x.Name)
.Aggregate((x, y) => x + ", " + y)
}).ToList();
return Json(lifts);
}
Then, once you have the ID on the View you use it to make the link using Html.ActionLink:
<%= Html.ActionLink("Person", "Index", new { id = p.Id })%>
If you know the action and controller beforehand, you can do something like:
var baseURL = '<%=Url.Action("MyAction","MyController") %>';
and then manually build your links from jQuery, with href set to something like baseUrl+"/"+personId