w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Get Class and object type from linq list query
You need to separate the concepts of "the field" from "the value of that field for a particular instance". You want FieldInfo.GetValue, e.g. var monitoringClass = (SystemClass) field.GetValue(null); EDIT: I note that SystemMonitoringClass.Computer is actually declared to return a value of type SystemClass, not SystemMonitoringClass - so you may want to change your cast appropriately, as I have above.

Categories : C#

Linq how to query a list of items for a combined list of a child collection based on a property of the parent item
You may just want to group the invoice headers by the group: var groups = invoiceHeader.GroupBy(ih => ih.Group); Then you can access the lines of the groups: foreach(var group in groups) { Console.WriteLine("Group " + group.Group); Console.WriteLine("Lines:"); Console.WriteLine(string.Join(", ", group.SelectMany(h => h.InvoiceHeader.InvoiceLines))); } Output would be something like Group A Lines: invoice1, invoice2, invoice3, invoice4 Group B Lines: invoice5, invoice6, invoice7, invoice8

Categories : C#

Using C# LINQ to concat a filtered List to List
If names is empty, what you're meant to do is this: var names = businessNames.Select(item => item.Name).ToList(); Another option is to use the List<T>'s ConvertAll method, like so: var names = buisnessNames.ConvertAll(item => item.Name); However, if it may be not empty, you'd need to use an if statement too: var names = new List<string>(); //some code if (names.Any()) names.AddRange(/*your selected method*/); else names = //your selected method;

Categories : C#

How to creat a new list from existing list with elements which contains the same id in Linq to object?
list.GroupBy(x => new { x.RefId, x.RefName }) .Select(g => new TestNew() { RefId = g.Key.RefId, RefName = g.Key.RefName, ListGroup = g.Select(y => new Group() { ID = y.ID, Name = y.Name }).ToList() }).ToList();

Categories : C#

Linq query to filter id inside a list of list c#
if skillId is a variable and assuming that SkillsList contains a property called Id. Then the following would work in getting you any data that has the specified skillId. var list = this._viewModel.Data.Where(t=>t.SkillsList.Any(s=>s.Id == skillId)); If Skillslist is just an array of integers then the following would work. var list = this._viewModel.Data.Where(t=>t.SkillsList.Any(s=> s == skillId)); Now if you are checking against a list the following would work. var list = this._viewModel.Data.Where(t=>t.SkillsList.Any(s=> skillsList.contains(s));

Categories : C#

Set property of a List which is also a List and from another linq query
You could try to join the tables directly instead of the hydrated results: from child in context.Children join user in context.UserInfos on child.userID equals user.ID select new ChildInfo() { ChildID = child.ID, UserId = user.ID, ChildName = child.Name }).ToList();

Categories : C#

How store a big list of strings to optimize both initialization time and search speed
Look at data structures like a patricia trie (http://en.wikipedia.org/wiki/Radix_tree) or a Ternary Search Tree (http://en.wikipedia.org/wiki/Ternary_search_tree). They will dramatically reduce your search time and depending on the amount of overlap in your strings may actually reduce the memory requirements. The Java collections are good for many purposes but are not optimal for large sets of short strings.

Categories : Java

LINQ to XML finding position in siblings list based on multiple attributes
It's quite easy: XElement rootElement = XElement.Parse( @"<scene id=""a""> <scene id=""b""> <scene id=""c"" type=""toc""> <scene id=""1"" type=""chapter""></scene> <scene id=""2"" type=""other""></scene> <scene id=""3"" type=""chapter""></scene> <scene id=""4"" type=""chapter""></scene> </scene> </scene> </scene>"); XElement sceneC = rootElement.Element("scene").Element("scene"); int theIndex = sceneC.Elements().TakeWhile(n => n.Attribute("id").Value != "3") .Count(x => x.Attribute("type").Value == "chapter");

Categories : Misc

LINQ Filter List inside another LINQ Query
The '.Where' lambda function needs to return a boolean value. Currently, you are returning the results of a '.Where' against another recordset. Instead, you probably intended something like this: var results = db.TableA .Where(t => t.idA == id) .Where(t => t.Association.Any(m => m.idB == 1)); The '.Any' function will return true if 't.Association' contains any records that match the condition.

Categories : C#

Should I be using a Dictionary or List with a linq search?
The second approach is not going to work, because arrays do not override the GetHashCode and Equals in a way that would use the data stored in the array. The first approach, however, would be slow for collections with high number of cells, because of a linear search. A better approach would be to use Tuple<sbyte,sbyte> instead of an array: Dictionary<Tuple<sbyte,sbyte>, Cell> CellList; //.... Cell thisCell = CellList[Tuple.Create(thisX , thisY)];

Categories : C#

Getting list of string(Collection) from an object using hibernate criteria
About you question: no, this projection is not possible because collection of elements has the same lifecycle of owner entity Getting collections of elements with criteria is not possibile (read here). You have to work with native SQL to return List<String>.

Categories : Java

Search list of object based on another list of object c#
Well, you could just use: bool hasCode = arts.Any(a => a.BarCode.Intersect(eans).Any()); That's assuming that either you want to treat each Ean object individually, or you've actually overridden Equals and GetHashCode appropriately. It would be more efficient to create a set though: var set = new HashSet<Ean>(eans); bool hasCode = arts.Any(a => a.BarCode.Any(e => set.Contains(e))); As an alternative approach, you could flatten your list to basically be a sequence of barcodes: bool hasCode = arts.SelectMany(a => a.BarCode) .Intersect(eans) .Any(); That's actually probably the cleanest approach, as you don't care about which article has the matching barcode.

Categories : C#

LINQ: search 2 properties for a list of strings
You are using the wrong LINQ method, you want Where instead of All: Questions = questions.Where(x => ...); All tells you if every item in the collection satisfies a condition (boolean result); Where filters the elements that satisfy the condition (filtered collection result). Depending on what Questions is exactly (looks like a property, of what type?) you may have to wrap it up with ToList or ToArray.

Categories : C#

Search in a List of List Object in C#
You can use Any()extension method to see if any of the string in list of strings matches your keyword- List<IntVector> newList = UserData.FindAll(s => s.ClientName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 || s.CustomerID.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 || s.AddInfo.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 || s.MobileNo.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 || s.CustomerInfo.Any(t => t.IndexOf(searchSt

Categories : C#

Python: Split a list into nested list at points where item matches criteria
Something like this: li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300] r = [[]] # start with a list containing an empty sub-list for i in li: if i >= 2000: # start a new sub-list when we see a big value r.append([i]) else: # append to the last sub-list of r r[-1].append(i)

Categories : Python

How can I filter a list of strings, creating a list containing only those meeting my criteria?
You can use LINQ to filter items with Length > 5 to your newFoo List List<string> newFoo = foo.Where(r => r.Length > 5).ToList(); If you want to use simple for loop then: for (int h = 0; h < foo.Count; h++) { if (foo[h] != null && foo[h].Length > 5) newFoo.Add(foo[h]); } (Remember to remove the ; semicolon at the end of your for-loop, currently it will not do anything since it will consider ; as the only statement for the loop to work on)

Categories : C#

vb.net linq list of object
I search the best way to concat both list grouping by Id. Like a Distinct. Use Enumerable.Union. However, you need to override Equals and GetHashCode in the class Item first. Then all Linq methods will use your ID: Class Item Public Property ID As Int32 Public Overrides Function Equals(obj As Object) As Boolean If obj Is Nothing Then Return False If Not TypeOf obj Is Item Then Return False Return Id = DirectCast(obj, Item).Id End Function Public Overrides Function GetHashCode() As Integer Return Id.GetHashCode() End Function End Class Now you can use Union which is efficient and clear: Dim list3 = list1.Union(list2).ToList MSDN: This method excludes duplicates from the return set. This is different behavior to the Co

Categories : Vb.Net

Linq Expression to Query Two List
In LINQ, you can have multiple from's if you want to query more than one data source, so for your problem I would do something like this: internal class Program { private static void Main(string[] args) { //The below code is just me pulling some data out of the air to work with var listOfIds = new List<ObjectA>(); var data = new List<ObjectB>(); for (var i = 0; i < 5; i++) { if (i % 2 == 0) { listOfIds.Add(new ObjectA(i)); } data.Add(new ObjectB(i, DateTime.Now.AddDays(i))); } //Now we have two ILists which match the type of data you were talking about, and you simply query them like so var datesWhereIdIsInList = (from id in listOfIds

Categories : C#

Using linq on a SharePoint list object
You probably want the Microsoft.Sharepoint.Linq namespace, instead of System.Linq. You can find it here. Microsoft also has some documentation on Linq to SharePoint here.

Categories : C#

How can I find object in List with Linq?
Using the Where keyword and a lambda like so: MyObject result = collectionMyObject.Where(x => x.Id == 2).FirstOrDefault() Or, to find in the Items sub-collection simply do: MyObject result = collectionMyObject.Where(x => x.Item.Id == 2).FirstOrDefault()

Categories : C#

Why hibernate Criteria not maintaining order in results of criteria.list()?
Criteria criteria = getCurrentSession().createCriteria(A.class, "a"); criteria.createAlias("a.listName1", "b", JoinType.LEFT_OUTER_JOIN); criteria.createAlias("b.listName2", "c", JoinType.LEFT_OUTER_JOIN); criteria.createAlias("c.listName3", "d", JoinType.LEFT_OUTER_JOIN); ProjectionList projections = Projections.projectionList(); projections.add(Projections.distinct(Projections.property("a.column_of_a"))); projections.add(Projections.property("b.column_of_b")); projections.add(Projections.property("c.column_of_c")); criteria.setProjection(projections); criteria.add(Restrictions.eq("a.column_of_a", someValue)); criteria.add(Restrictions.eq("c.column_of_c", someValue)); criteria.addOrder(Order.asc("a.column_of_a")); criteria.addOrder

Categories : Java

is it possible to get a left join list out a linq query
I previously posted code which was not a proper left-outer join.. It wouldnt return an account if no orders were associated. In this code that has been fixed: var aom = from a in accounts join ao in accountorders on a.ID equals ao.AccountID into aoGroup from aod in aoGroup.DefaultIfEmpty(new AccountOrder()) join o in orders on aod.OrderID equals o.ID into oGroup group oGroup by a into g select new AccountOrderModel() { Name = g.Key.Name, orders = g.SelectMany(x => x).ToList() }; It has been tested and i think i finally got it correct.

Categories : C#

query list with linq lambda expressions
participants = participants .Where(p => counties.Any(c=> c.CountyId == p.CountyOfParticipationId) ) Or participants.Where(p => p.County.CollaborationId == collaborationId) should also work if you have set up relations properly

Categories : C#

How to query a Datatable using LINQ and add values to a List?
This can be done using Select and ToList: var lstProductData = dtReport.Rows.Cast<DataRow>() .Select(row => new ProductData(new Guid(row["ProductID"].ToString()) , row["Product"].ToString())) .ToList();

Categories : C#

Linq to return a new object with a selection from the list
Run the following in LinqPad (LinqPad.com) void Main() { List<A> IDs= new List<A>() { new A() { ID = "1", Values = new List<B>() { new B { Code = "1", DisplayName = "1"}, new B { Code = "2", DisplayName = "2"}, new B { Code = "3", DisplayName = "3"} } }, new A() { ID = "4", Values = new List<B>() { new B { Code = "4", DisplayName = "4"}, new B { Code = "5", DisplayName = "5"}, new B { Code = "6", DisplayName = "6"} } }, new A() { ID = "7", Values = new List<B>() { new B { Code = "7", DisplayName = "7"},

Categories : C#

Ascending and descending of list object in c# using LINQ
orderby requires lambda for key selector: public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector ) but you are trying to pass simple string. This will not work. Try to use Dynamic Linq if you want to sort results based on some string. Get System.Linq.Dynamic from NuGet and apply sorting this way (assume firstExpression looks like propertyname + asc/desc): var firstExpression = "empid asc"; var queryResultorderby = objList.AsQueryable() .OrderBy(firstExpression);

Categories : C#

Union two nested List with LINQ
It can be possible with LINQ with the help of SelectMany function. YOu can find the example of SelectMany Here

Categories : C#

Is it possible to apply query rules to a LINQ to SQL association list?
I'm not familiar with Linq-to-SQL (more with EF) but I imagine this would be tackled if, say, all your classes that have that property share a common interface, for example: public interface IHasActive { bool Active { get; set; } } Then you can implement an extension method: public static class IHasActiveExtensions { public static IQueryable<T> ExcludeInactive<T>(this IQueryable<T> query) where T : IHasActive { return query.Where(m => m.Active); } }

Categories : C#

aggregate and distinct linq query output to list
Use GroupBy and Sum: var result = db.Table .GroupBy(r => r.Date) .Select(g => new{ Day=g.Key, Hours=g.Sum(r=> r.Hours) }) If Date is actually a DateTime you should use r.Date.Date to remove the time portion.

Categories : C#

linq remove items from query where any list value is present
Is this what you're after? MyTable.Where(a => !UserIds.Contains(a.Id)) This will select everything from MyTable where the Id is not in UserIds.

Categories : C#

Linq anonymous type with list object property
You need to take the collection of desks from the data model, convert each one to a DeskViewModel, and convert the resulting sequence to a List<T>. That would look something like p.Desks.Select(d => new DeskViewModel { ... }).ToList()

Categories : C#

Compare elements of an object resides in two list - one on one using LINQ
Use Enumerable.Zip if you are comparing one by one: House.Windows.Zip(House1.Windows, (w, w1) => w.color != w1.color); This returns collection of boolean values for one by one comparison of colors. You can use Any(b => !b) to check if there is any non equal color. Keep in mind, that both windows lists should have same length (only corresponding elements will produce result). So, you can start from checking length of lists before doing zip. If items count is different, then lists are not same. In order to compare windows you should override Equals and GetHashCode methods: public class Window { public string Size { get; set; } public string Color { get; set; } public bool IsEnergySaving { get; set; } public Window() { } public Window(string size, string co

Categories : C#

How to update a particular field of a particular object in Generic list in c#.net using LINQ
LINQ is all about querying, not updating. You can use LINQ to get all managers from the list, var managers = from e in emplst where emplst.Any(x => x.mgrid == e.ecode.ToString()) select e; or using JOIN (it would require implementing Equals and GetHashCode methods on Employee class to make Distinct work: var managers = (from e in emplst join e2 in emplst on e.ecode.ToString() equals e2.mgrid select e).Distinct(); and then iterate over and change the salary: foreach(var manager in managers) manager.salary *= 1.1;

Categories : Linq

How to create a list from filtering 2 lists with linq to object
With your requirement, I think we should use Any method, therefore we should write method query not expression query. Of course I don't know the equivalent of Any in expression query (At least it should be short as in the method query, otherwise, it's not good). If any one knows, please leave some comment. Thanks for that. var FilteredAList = ListOfA.Where(x=>ListOfB.Any(y=>x.Code==y.Code && y.Name=="yoda")) .ToList<A>();

Categories : C#

Filter LINQ query using items from an external list with Lambda
Assuming that by "with lambda" you mean the "query syntax", you can rewrite your query like this: var myProducts = db.Products.Where(p => productList.Contains(p.ProductID));

Categories : Linq

How can I speed this LINQ query up?
Since you're merely returning the count, you can compute it in your query using the Count method: using (OEContext context = new OEContext()) { var query = from ha in context.HousingAssignments where ((ha.BedID == bed.ID) && (((ha.CheckIn <= checkin) && (ha.CheckOut >= checkin)) || ((ha.CheckIn <= checkout) && (ha.CheckOut >= checkout)))) select ha; return query.Count(); } This eliminates pulling the values from your database locally, storing into the list, then "throwing away" the results. Instead, the count will get computed on the server, and you'll only pull a single number across. You can also potentially speed up the query on the server with proper indexing of the CheckIn and CheckOut columns.

Categories : C#

Speed up LINQ query - EF5
I can't judge whether it will speed up things, but your homemax and awaymax queries could be var homemax = from t in homecomps group t by t.teamId into grp select grp.OrderByDescending(x => x.compId).FirstOrDefault(); var awaymax = from t in awaycomps group t by t.teamId into grp select grp.OrderByDescending(x => x.compId).FirstOrDefault(); Further, as you are composing one very large query it may perform better when you cut it up in a few smaller queries that fetch intermediary results. Sometimes a few more roundtrips to the database perform better than one very large query for which the database engine can't find a good execution plan. Another thing is all these Distinct()s. Do you always need them? I think you can do wit

Categories : Linq

compare list type year's value with datetime column in linq to sql query
I'll take a stab at this and recon you need something along the lines of: from d in context.tbl_pl_data where (d.lng_clientid.Equals(ClientId) && d.str_name.Equals(name) && d.int_deleted.Equals(0) && d.dte_cr_on.Year.Contains(Session["UserYearSelected"]) If there's multiple years however, you'll probably need to convert Session["UserYearSelected"] into a string[] Obviously can't test your query or check it compiles but hopefully it'll help you. You can also have a look at this for further help.

Categories : Linq

List within a List - How to put new line with LinQ after List within List is over?
Console.Write( String.Join(Environment.NewLine, f.Select(flight => { var segments = flight.Segments.Where(x => x.DepartureDate > DateTime.Now); return String.Join(" ", segments.Select(segment => { return String.Format("Departure: {0}, Arrival: {1};", segment.DepartureDate, segment.ArrivalDate)); }); }); ); I personally prefer to have a Joined extension method on IEnumerable<T> which wraps String.Join (taking a delimiter and an optional transformation delegate), and a Formatted extension method on String which wraps String.Format: var output = f.Joined(Environment.NewLine, flight => flight.Segments .Where(s => s.DepartureDate > DateTime.Now) .Joined(" ", s => "Departure:

Categories : C#

Insert list of attributes into list of objects in python
I'd do something like this: for i, o in enumerate(objs): o.attr = i enumerate(objs) is sort of like zip(range(len(objs)), objs), so in case you actually want to take values from another sequence, you can: for i, o in zip(sequence, objs): o.attr = i For efficiency you might use itertools.izip there too.

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.