score:29
you can use a .where
method with lambda that accepts the element index as its second parameter:
int[] somearray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
int[] newarray = somearray.where((e, i) => i < 5 || i >= somearray.length - 5).toarray();
foreach (var item in newarray)
{
console.writeline(item);
}
output:
0, 1, 2, 3, 4, 14, 15, 16, 17, 18
score:1
please try this:
var result = somearray.take(5).union(somearray.skip(somearray.count() - 5).take(5));
score:2
try this:
int[] somearray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
var firstfiveresults = somearray.take(5);
var lastfiveresults = somearray.reverse().take(5).reverse();
var result = firstfiveresults;
result = result.concat(lastfiveresults);
the second reverse() reorders the numbers so you won't get 18,17,16,15,14
score:3
this should work
somearray.take(5).concat(somearray.skip(somearray.count() - 5)).take(5);
score:4
try this:
var result = somearray.where((a, i) => i < 5 || i >= somearray.length - 5);
score:6
in case you are not playing code puzzles with your co-workers, but just want to create a new array with your criteria, i wouldn't do this with queries at all, but use array.copy.
there are three distinct cases to consider:
- the source array has fewer than 5 items
- the source array has 5 to 9 items
- the source array has 10 or more items
the third one is the simple case, as the first and last 5 elements are distinct and well defined.
the other two require more thought. i'm going to assume you want the following, check those assumptions:
if the source array has fewer than 5 items, you will want to have an array of 2 * (array length) items, for example [1, 2, 3] becomes [1, 2, 3, 1, 2, 3]
if the source array has between 5 and 9 items, you will want to have an array of exactly 10 items, for example [1, 2, 3, 4, 5, 6] becomes [1, 2, 3, 4, 5, 2, 3, 4, 5, 6]
a demonstration program is
public static void main()
{
console.writeline(string.join(", ", headandtail(new int[]{1, 2, 3})));
console.writeline(string.join(", ", headandtail(new int[]{1, 2, 3, 4, 5, 6})));
console.writeline(string.join(", ", headandtail(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11})));
}
private static t[] headandtail<t>(t[] src) {
int runlen = math.min(src.length, 5);
t[] result = new t[2 * runlen];
array.copy(src, 0, result, 0, runlen);
array.copy(src, src.length - runlen, result, result.length - runlen, runlen);
return result;
}
which runs in o(1);
if you are playing code puzzles with your co-workers, well all the fun is in the puzzle, isn't it?
it's trivial though.
src.take(5).concat(src.reverse().take(5).reverse()).toarray();
this runs in o(n).
score:11
a solution with arraysegment<>
(requires .net 4.5 (2012) or later):
var result = new arraysegment<int>(somearray, 0, 5)
.concat(new arraysegment<int>(somearray, somearray.length - 5, 5));
and a solution with enumerable.range
:
var result = enumerable.range(0, 5).concat(enumerable.range(somearray.length - 5, 5))
.select(idx => somearray[idx]);
both these solution avoid iterating through the "middle" of the array (indices 5 through 13).
Source: stackoverflow.com
Related Query
- Take the first five elements and the last five elements from an array by one query using LINQ
- Can I take the first n elements from an enumeration, and then still use the rest of the enumeration?
- find list elements which are similar to other list elements by 3 properties and then add value from the second one to the first
- Get all elements but the first from an array
- I'm trying to simplify with linq a statement that takes 2 lists of numbers and subtracts the first one from the second one
- Is possible with LINQ to extract from an array of objects the value of one property and create a new array?
- Generating an array of integers with distinct numbers and the first one cannot be zero
- Split elements of a list and retrieve only the first part from the split
- Take a sequence of elements from an array from i to j using C# and extension method
- How can I group by in LINQ and then take first from the group from a sequential set of checks
- How can I use linq to remove a certain string from an array while it exists as the first or last element
- Excluding one item from list (by Index), and take all others
- Split the string and join all first elements then second element and so on in c#
- Left join on two Lists and maintain one property from the right with Linq
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- How to understand the following C# linq code of implementing the algorithm to return all combinations of k elements from n
- linq extension method to take elements from the end of the sequence
- linq query to join two tables and get the count from one table values from the other
- Calculate duration between first login and last logout from a set of records in datatable
- Why does adding a list to another list, using add range, remove the elements from the first list?
- Group a collection and take first 5 from each group
- How to take elements from range with lambda expressions and linq?
- I want take the last 4 record but always get the first 4
- How to Remove elements from one List based another list's element and condition?
- Get first item and last item if it exists from a group
- Is a full list returned first and then filtered when using linq to sql to filter data from a database or just the filtered list?
- How to retrieve one table row and list of rows that are connected to the first row in Linq .NET
- get attribute value from multiple elements with same name and attribute value of one other element in xml
- How to iterate at elements from a sub list and then remove the sub list from the list? With great performance
- How to get the first and the last parts of string separated by a space
More Query from same tag
- Checking the name and value of an XML node, using LINQ
- ReactiveUI "Compelling Example" search with Caliburn.Micro.ReactiveUI
- Workaround for DefaultIfEmpty
- c# returning class implementation in lambda
- LINQ querying nested dictionary with multiple key value selection in C#
- How to Invoke this linq query?
- LINQ to find first available numbered-suffix string
- How to Union two Queries in LINQ to Fluent NHibernate?
- Take pages and combine to list of pages
- LINQ to objects cast result of query
- C# Create Dictionary with All Non-Object Property Names Mapped to the Object's Structure
- ForEach Extension Method for ListItemCollection
- Linq many to many select query with Distinct
- comma separated list items with brackets in linq
- ArgumentException calling Expression.IfThenElse
- Entity Framework Relationships Foreach
- Is it possible to cancel select and 'Continue' within .Select statement upon a condition?
- Best way to write DataTables from a Web Service into XML?
- Read text file word-by-word using LINQ
- ASP.NET - Entity Framework - Only parameterless constructors and initializers are supported in LINQ to Entities
- Search for similar values in 2 arrays
- Selecting only one column linq lambda query asp.net
- Why is dbcontext disposed before the foreach loop
- The left-hand side of an assignment must be a variable property or indexer
- Does modeling entity-relationship using SQL Server built-in "Diagrams" have performance benefits on the execution of queries?
- Group by two properties as one in Linq
- Read rss feeds with c# mvc4
- How do lambda parameters work?
- how to create a pivot table with dynamic column using linq tree expression
- Pass in an Expression to linq's Select