How to Get First N Elements of a List in C#

How to get first N elements of a list in C#?


var firstFiveItems = myList.Take(5);

Or to slice:

var secondFiveItems = myList.Skip(5).Take(5);

And of course often it's convenient to get the first five items according to some kind of order:

var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);

How to set the value to the first N elements of a list?

Why not just a regular for loop?

for (int i = 0; i < Data.Count(); i++ )
{
Data[i].NodeColor = (i < 3 ? Colors.Red : Colors.Green);
}

I personally think that is more readable than it would be in LINQ, but as always, your mileage may vary.

Get the first few elements from List on C#

If you have C# 3, use the Take extension method:

var list = new [] {1, 2, 3, 4, 5};

var shortened = list.Take(3);

See: http://msdn.microsoft.com/en-us/library/bb503062.aspx

If you have C# 2, you could write the equivalent:

static IEnumerable<T> Take<T>(IEnumerable<T> source, int limit)
{
foreach (T item in source)
{
if (limit-- <= 0)
yield break;

yield return item;
}
}

The only difference is that it isn't an extension method:

var shortened = SomeClass.Take(list, 3);

Can I take the first n elements from an enumeration, and then still use the rest of the enumeration?

This is an interesting question, I think you can use a workaround like this, instead of using LINQ get the enumerator and use it:

private void ReadCsv(IEnumerable<string> records)
{
var enumerator = records.GetEnumerator();
enumerator.MoveNext();
var headerRecord = enumerator.Current;
var dataRecords = GetRemainingRecords(enumerator);
}

public IEnumerable<string> GetRemainingRecords(IEnumerator<string> enumerator)
{
while (enumerator.MoveNext())
{
if (enumerator.Current != null)
yield return enumerator.Current;
}
}

Update: According to your comment here is more extended way of doing this:

public static class CustomEnumerator
{
private static int _counter = 0;
private static IEnumerator enumerator;
public static IEnumerable<T> GetRecords<T>(this IEnumerable<T> source)
{
if (enumerator == null) enumerator = source.GetEnumerator();

if (_counter == 0)
{
enumerator.MoveNext();
_counter++;
yield return (T)enumerator.Current;
}
else
{
while (enumerator.MoveNext())
{
yield return (T)enumerator.Current;
}
_counter = 0;
enumerator = null;
}
}
}

Usage:

private static void ReadCsv(IEnumerable<string> records)
{
var headerRecord = records.GetRecords();
var dataRecords = records.GetRecords();
}

How can select first 3 item of list

You can use the Take() method

List<aspnet_News> allNews = context.aspnet_News.OrderByDescending(i => i.NewsId)
.Take(3) // Takes the first 3 items
.ToList();

It'll also handle the case where the list contains less than 3 items and take them only.

Take first n elements from System.Collections.Generic.IEnumerable

Put Take before materialization (ToList):

List<CustomObject> tempList = DataBase.GetAllEntries()
.Take(5)
.Cast<CustomObject>()
.ToList();

Let materialization be the final operation.

Query a list and select top 10 values

You can order the list by descending Frequency and then take the first 10 like this:

var top10 = objectList.OrderByDescending(o => o.Frequency).Take(10);

How to get first and last values from list string ?

You can use List<string> as an array like;

List<string> _ids = new List<string>() { "aaa", "bbb", "ccc", "ddd" };
var first = _ids[0]; //first element
var last = _ids[_ids.Count - 1]; //last element

With using LINQ, you can use Enumerable.First and Enumerable.Last methods.

List<string> _ids = new List<string>() { "aaa", "bbb", "ccc", "ddd" };
var first = _ids.First();
var last = _ids.Last();
Console.WriteLine(first);
Console.WriteLine(last);

Output will be;

aaa
ddd

Here a DEMO.

NOTE: As Alexander Simonov pointed, if your List<string> is empty, First() and Last() will throw exception. Be aware of FirstOrDefault() or .LastOrDefault() methods.

How to get first object out from List Object using Linq

Try:

var firstElement = lstComp.First();

You can also use FirstOrDefault() just in case lstComp does not contain any items.

http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx

Edit:

To get the Component Value:

var firstElement = lstComp.First().ComponentValue("Dep");

This would assume there is an element in lstComp. An alternative and safer way would be...

var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null)
{
var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}


Related Topics



Leave a reply



Submit