w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Split List into Sublist using Linq based on content of list
Maybe? var list = new List<int>() { 1, 2, 0, 3, 4, 5, 0, 6 }; var subLists = list.Split(0).ToList(); IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, T divider) { var temp = new List<T>(); foreach (var item in list) { if (!item.Equals(divider)) { temp.Add(item); } else { yield return temp; temp = new List<T>(); } } if (temp.Count > 0) yield return temp; }

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#

LINQ method to sort a list based on a bigger list
Well the simple - but inefficient - way would be: var result = _lstNeedToOrder.OrderBy(x => _lstOrdered.IndexOf(x)); An alternative would be to work out a far way of obtaining the desired index of a value. If your values will always in be the range [1...n] you could just invert that "ordered" list to be a "list of indexes by value". At which point you could use: var result = _lstNeedToOrder.OrderBy(x => indexes[x]); (where indexes would have an extra value at the start for 0, just to make things simpler). Alternatively, you could create a Dictionary<int, int> from value to index. That would be more general, in that it would handle a very wide range of values without taking a lot of memory. But a dictionary lookup is obviously less efficient than an array or list lookup.

Categories : C#

Using LINQ to split items within a list
Use SelectMany to flatten results of splitting each name by : names.SelectMany(n => n.Split(':')) .Dump();

Categories : C#

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#

Remove element from list if it satisfies a condition defined from a separate list - Python
This will produce the list you seek. The key is to use zip (or izip if you prefer) when you have lists with corresponding elements. [offset for offset, ratio in zip(Offset, Ratio) if ratio < 2.5]

Categories : Python

Split string into list of N-length strings using LINQ
string s = "ABCDEFGHIJKLMNOPQRSTUVWX"; var results = s.Select((c, i) => new { c, i }) .GroupBy(x => x.i / 4) .Select(g => String.Join("",g.Select(y=>y.c))) .ToList(); You can also use morelinq's batch var res = s.Batch(4).Select(x => String.Join("", x)).ToList(); If you don't mind using side effects, this is possible too var res2 = s.SplitEvery(4).ToList(); public static IEnumerable<string> SplitEvery(this string s, int n) { int index = 0; return s.GroupBy(_=> index++/n).Select(g => new string(g.ToArray())); } And Of course every string operation question deserves a Regex answer :) var res3 = Regex.Split(s, @"(?<=G.{4})");

Categories : C#

Divide list and append the list to separate lists python
Use Python slice notation: a = ['name', '2', 3, 4, 5, 'a', 'b', 'c', 'd', 10, 4, 'lol', '3'] n = len(a) print(n) mid = n // 2 list1, list2 = a[:mid], a[mid:] print(list1) print(list2)

Categories : Python

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 to split a list into a list of lists by removing a specific separation(Haskell)
I will try to help you develop the understanding of how to develop functions that work on lists via recursion. It is helpful to learn how to do it first in a 'low-level' way so you can understand better what's happening in the 'high-level' ways that are more common in real code. First, you must think about the nature of the type of data that you want to work with. The list is in some sense the canonical example of a recursively-defined type in Haskell: a list is either the empty list [] or it is some list element a combined with a list via a : list. Those are the only two possibilities. We call the empty list the base case because it is the one that does not refer to itself in its definition. If there were no base case, recursion would never "bottom out" and would continue indefinitely!

Categories : List

Linq expression to filter an a list of entity's collection, and maintain list of entities
var r = Foos.Select(x => new Foo() { Id = x.Id, Name = x.Name, Bars = x.Bars.Where(y => y.Age <= 25 && y.Age >= 5).ToList() });

Categories : C#

Turning a chain of foreach's for inserting elements from a list into another list into linq
What you're logically doing here is a Join operation. Your current code is actually finding all possible pairs of cities and states and then filering only the pairs that match. You could represent that in LINQ, but you wouldn't want to. There are more efficient ways of performing a Join that only generate the exact pairs that you need to begin with. The LINQ Join operator leverages this. Your code boils down to two different Join calls, and then an iteration over each result that performs the mutation of the objects based on the query. var stateCityPairs = from state in finalList join city in cityList on state.IdState equals city.IdState select new { state, city }; foreach (var pair in stateCityPairs) pair.s

Categories : C#

Using linq group by to get from a list of objects with a DateTime property to a list with an interval StartDate, EndDate
You can use GroupBy in combination with SelectMany and Aggregate for this: var setups = bookedRooms.GroupBy(x => Tuple.Create(x.TimePeriodId, x.VenueId)) .SelectMany(x => x.Aggregate( new List<EventSetup>(), AccumulateRooms)) .OrderBy(x => x.StartDate) .ToList(); List<EventSetup> AccumulateRooms(List<EventSetup> existingSetups, BookedRoom currentRoom) { var setup = existingSetups.LastOrDefault(); if(setup == null || setup.EndDate.AddDays(1) != currentRoom.Day.Date) { setup = new EventSetup { VenueId = currentRoom.VenueId, TimePeriodId = currentRoom.TimePeriodId, StartDate = currentR

Categories : C#

File in a list and then split every term in the list, python
change for r in resid_list into for r in resid_list[0] Since you are using list comprehension, your parameter looks like this: In [9]: resid_list Out[9]: [['IA45', 'TA43', 'WB58', 'AB71']] i.e. a list of lists In [10]: resid_list[0] Out[10]: ['IA45', 'TA43', 'WB58', 'AB71'] gives you what you want.

Categories : Python

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#

separate list into multiple lists based on property
Yes, you can do it with LINQ in a single statement: public List<List<IGrid>> Separat(List<IGrid> source) { return source .GroupBy(s => s.RowIndex) .OrderBy(g => g.Key) .Select(g => g.ToList()) .ToList(); } If you do not care that the lists appear in the ascending order of RowIndex, the way that your method produces them, you can remove the OrderBy method call from the chain of method invocations.

Categories : C#

A distinct list based on split values
The only way I can think of doing this (in XSLT 1.0) is by means of a "two-pass" transform. Effectively, you perform two transforms (although this can be done in a single stylesheet, as I am going to demonstrate). The first transform will split your current VariantCode attributes into separate elements, so the result is like so <Item ProductId="1001@@SHOP1"> <Variant>1616_42</Variant> <Variant>1615_01</Variant> <Variant>ct_HD</Variant> </Item> The second transform can then use a technique called Muenchian Grouping to output the distinct Variant elements you require. For this to work, the results of the first transform are simply stored in a variable <xsl:variable name="variantSplit"> <xsl:apply-templates select="

Categories : List

Split ArrayList into multipleList based on the value in the list
With Guava: ListMultimap<String, MyProduct> result = Multimaps.index(productList, new Function<String, Product>() { @Override public String apply(Product input) { return input.getTitle(); } }); With plain old Java collections: Map<String, List<MyProduct>> result = new HashMap<>(); for (MyProduct p : productList) { List<MyProduct> list = result.get(p.getTitle()); if (list == null) { list = new ArrayList<>(); result.put(p.getTitle(), list); } list.add(p); } Both assume that a "similar" title is actually an "equal" title.

Categories : Java

R Split character vector of file paths into list by parent directory?
You could combine split and dirname: path <- c("/home/username/data/dir/GCZ98/GCZ98_1998_12_16.asc.gz", "/home/username/data/dir/GCZ98/GCZ98_1998_12_20.asc.gz", "/home/username/data/dir/GCZ99/GCZ99_1999_12_21.asc.gz", "/home/username/data/dir/GCZ99/GCZ99_1999_12_23.asc.gz", "/home/username/data/dir/GCZ99/GCZ99_1999_12_27.asc.gz", "/home/username/data/dir/GCZ99/GCZ99_1999_12_28.asc.gz") ## split by basedir split(path, dirname(path)) # $`/home/username/data/dir/GCZ98` # [1] "/home/username/data/dir/GCZ98/GCZ98_1998_12_16.asc.gz" "/home/username/data/dir/GCZ98/GCZ98_1998_12_20.asc.gz" # # $`/home/username/data/dir/GCZ99` # [1] "/home/username/data/dir/GCZ99/GCZ99_1999_12_21.asc.gz" "/home/username/data/dir/GCZ99/GCZ99_1999_12_23.asc.gz"

Categories : Regex

Select in LINQ all keys from List of List of KeyValuePairs
It sounds like you just need a combination of SelectMany, Select and Distinct: var allKeys = sourceData.SelectMany(list => list) // Flatten to a sequence of KVP .Select(kvp => kvp.Key) // Select just the keys .Distinct(); Note that if you want to iterate over allKeys more than once, you probably want to materialize the query, e.g. by calling ToList at the end: var allKeys = sourceData.SelectMany(list => list) // Flatten to a sequence of KVP .Select(kvp => kvp.Key) // Select just the keys .Distinct() .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#

How to iterate through an unordered list and then select the parent div of the list item
$('.question').filter(function () { return ! $(this).find('input:checked').length; }).addClass('highlight'); Here's the fiddle: http://jsfiddle.net/XTDre/

Categories : Javascript

How do i split a list into smaller lists based on keywords? (C# XNA)
You can use something similar to this: var lines = File.ReadAllLines( path ) .Select( s => s.Trim( ) ) .Where( s => s.Length > 0 ).ToArray( ); int index = 0; void Next() { index++; } bool Peek(string token ) { return lines[index].StartsWith( token ) ;} string ReadStringValue ( ) { var value = lines[index].Split( ' ' )[1]; Next( ); return value; }; string ReadIntValue () { var value = lines[index].Split( ' ' )[1]; Next( ); return int.Parse(value); }; Header ReadAnimation() { var anim= new Animation(); while (index<lines.Length) { if (Peek("num_fr

Categories : C#

Python: Split list based on first character of word
Use itertools.groupby() to group your input by a specific key, such as the first letter: from itertools import groupby from operator import itemgetter for letter, words in groupby(sorted(somelist), key=itemgetter(0)): print letter for word in words: print word print If your list is already sorted, you can omit the sorted() call. The itemgetter(0) callable will return the first letter of each word (the character at index 0), and groupby() will then yield that key plus an iterable that consists only of those items for which the key remains the same. In this case that means looping over words gives you all items that start with the same character. Demo: >>> somelist = ['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', '

Categories : Python

Rename the Parent of Expandable List as the name of Child of the List?
Replace the content at clicked position of mGroupCollection by child and invoke adapter .notifyDataSetChanged(). public class MainActivity extends Activity implements OnChildClickListener { private ExpandableListView mExpandableListView; private List<GroupEntity> mGroupCollection; private ExpandableListAdapter adapter = null; String URL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); prepareResource(); initPage(); mExpandableListView .setOnGroupExpandListener(new OnGroupExpandListener() { @Override public void onGroupExpand(int arg0) {

Categories : Android

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#

Create List of Tuples from List using LINQ
It can be achieved (example for Tuple<Single, Single>) and the following solution isn't very complex, but using loop is clearer and - in case of this particular solution - more efficient (the input list is enumerated twice). Code in C#, don't know VB var even = inputList.Where((elem, ind) => ind % 2 == 0); var odd = inputList.Where((elem, ind) => ind % 2 == 1); var outputList = even.Zip(odd, (a, b) => new Tuple<Single, Single>(a, b)).ToList();

Categories : Dotnet

LINQ sort a flat list based on childorder
Try this: public class Item { public int ID { get; set; } public int? ParentID { get; set; } public string Name { get; set; } public int SortOrder { get; set; } } public void DoWork() { Item[] data = new Item[] { new Item() { ID = 2, ParentID = 1, Name = "Test 2", SortOrder = 1}, new Item() { ID = 3, ParentID = 1, Name = "Test 3", SortOrder = 2}, new Item() { ID = 4, ParentID = 2, Name = "Test 4", SortOrder = 1}, new Item() { ID = 1, ParentID = null, Name = "Test 1", SortOrder = 1}, }; var result = from x in data orderby x.SortOrder, x.ParentID select x; foreach (var row in result.ToArray()) { Console.WriteLine(row.Name);

Categories : C#

How to create alphabetical based list as Sencha touch grouped list but in jQuery?
You can use data-autodividers="true" Check here http://view.jquerymobile.com/1.3.1/dist/demos/widgets/listviews/ DEMO http://jsfiddle.net/yeyene/5kfnT/6/ You can also use data-filter-reveal="true" to hide or show. For A-to-Z list navi bar I am not sure you can use with this plugin + JQM or not. Check here http://devgrow.com/slidernav-jquery-plugin/ Author page http://devgrow.com/slidernav/

Categories : Jquery

List multiple models in class based list and detail views in django
You can add extra context variables by overriding the get_context_data() function in your class: class MultipleModelsListView(ListView): model = TaskA # Class names should use capitalized CamelCase def get_context_data(self, **kwargs): kwargs = super(MultipleModelListView, self).get_context_data(**kwargs) kwargs.update({ 'taskb_list': TaskB.objects.all(), # or with some filter applied 'taskc_list': TaskC.objects.all(), 'taskd_list': TaskD.objects.all(), }) return kwargs This will give you, additional to the default context supplied by a ListView, the context variables taskb_list, taskc_list and taskd_list to iterate over. You can iterate over these in your template like this: {% for task in object_list %} {#

Categories : Django

Can List.Distinct() apply to the list type of List>?
That's because List<T> has no Equals and GetHashCode implemented, so standard reference comparison is being performed. And it returns false, because you have two separated lists. You can write your own IEqualityComparer<List<string>> implementation and provide it as Distinct method parameter. Within the comparer you can use Enumerable.SequenceEqual) method to check if lists has the same content.

Categories : C#

vba to search a list and colour code matches based on a contents list.
I hate to encourage you, because you did not follow the site rules that say to research and attempt a solution before asking a quesiton, and share what you have already tried. That is probably why others have given your question a negative rating. However, you did enough thinking about the parameters of your problem, that I suspect you may have tried something before composing this question, and I'm granting you the benefit of the doubt. Here is a possible solution, if by "pre colour coded data" you mean the interior of the cell. Change the Constants at the top to match the column and header row of your data. If the pre colour coding of your data is something other than the interior settings I've used, you can take Marty McVry's advice of using the macro recorder to determine which set

Categories : Excel

How to make a list in Python distinct based on a property of the class in the list?
Assuming the property you wish to key on is immutable, you can use a dict: d = {} for x in xs: d[x.tag] = x Now d will contain a single x per tag value; you can use d.values() or d.itervalues() to get at the xs. NB. here last matching item wins; to have the first one win, iterate in reverse.

Categories : Python

Removing class of nested list elements based off click on outer list element?
You need this on click of A- $(this).closest('ul').find('li.active').removeClass('active'); $(this).closest('li').addClass('active') Demo -------> http://jsfiddle.net/NrGGz/

Categories : Javascript

Split a Datatable into multiple Datatables based on a list of column names
you may want to use System.Linq.Dynamic var dt = new DataTable(); var res = new List<DataTable>(); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("Country", typeof(string)); dt.Columns.Add("Supplier", typeof(string)); dt.Rows.Add(515, "DE", "A"); dt.Rows.Add(515, "CH", "A"); dt.Rows.Add(515, "FR", "A"); dt.Rows.Add(516, "DE", "B"); dt.Rows.Add(516, "FR", "B"); dt.Rows.Add(517, "DE", "C"); dt.Rows.Add(517, "IT", "C"); var fields = new List<string>() { "Supplier", "Country"}; var qfields = string.Join(", ", fields.Select(x => "it["" + x + ""] as " + x)); // qfields = "it["Supplier"] as Supplier, it["Country"] as Country" var q = dt .AsEnumerable() .AsQueryable() .GroupBy("new(" + qfields + ")", "it") .Select("new (it as Data)"); foreach (dynamic d in q

Categories : C#

Getting List for Select tag from Map> based in iterator index
When iterating a map via the iterator tag var attribute is not necessary, because the current item pushed to the value stack on each iteration. So, referencing value attribute of the map entry as a list collection. <s:iterator value="listOne" status="stat"> <s:select name="col%{#stat.index}" listKey="KEY" listValue="VALUE" list="dynamicList['%{top}']" /> </s:iterator>

Categories : Java

Filter a list based on many parameters and gather the result in another list
If you don't have a strong reason not to, it probably makes sense to filtering on the three fields simultaneously: var filteredCards = from card in mListCards where _color == "ALL" || card.mCardColor == _color where _type == "ALL" || card.mCardType == _type where _rarity == "ALL" || card.mCardRarity == _rarity select card;

Categories : C#

Populate Telerik Drop-down list based on what is selected in other list
You can do it like this: View: <p> <%: Html.Label("Type") %> <%: Html.Telerik().DropDownList().Name("Type") .HtmlAttributes(new { id = "type" }) .Items(items => { items.Add().Text("").Value(""); items.Add().Text("Numbers").Value("1"); items.Add().Text("Alphabets").Value("2"); }) .CascadeTo("Values") %> </p> <p> <%: Html.Label("Values" %> <%: Html.Telerik().DropDownList().Name("Values") .HtmlAttributes(new { id = "values" }) .DataBinding(b => b.Ajax().Select("GetDropDownValues", "Home")) %> </p> Controller: public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public JsonResult GetDropDo

Categories : C#

How to pre-select a drop down option list based on the parent key
Here is how you should do it: public ActionResult Create(int? rackID) { var model = new ServerJoin() { IsIPUnique = true, IsMACUnique = true}; if(rackID.HasValue) { model.RackID = rackID.Value; } PopulateViewBagData(); return View(model); } Then, in your View, you can use an if clause to replace the DropDownList with a Hidden input if the Model has a RackID. The ActionLink in your Rack View is correct.

Categories : Asp Net



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