Home > Enterprise >  I am trying to return a list of records in c#
I am trying to return a list of records in c#

Time:12-16

I have a fixed list of

List<int> values = new List<int>() {0, 1, 2, 3, 4, 5, 6};

I can give 2 input named startValue and endValue and it will return a List<int>.

Examples:

#1

startValue = 0
endValue = 4
returned List: {0, 1, 2, 3, 4} 

#2

startValue = 1
endValue = 6
returned List: {1, 2, 3, 4, 5, 6} 

#3

startValue =  6
endValue = 4
returned List: {6, 0, 1, 2, 3, 4} 

I have implemented in linq.

List<int> days = new List<int> { 0, 1, 2, 3, 4, 5, 6 };
List<int> excpt = new List<int> { startDay, endDay };
List<int> fDays = new List<int>();

fDays = days.Except(excpt).ToList();

CodePudding user response:

My idea would be to use LinkedList collection like that:

List<int> days = new List<int> { 0, 1, 2, 3, 4, 5, 6 };

var startDay = 6;
var endDay = 4;

var linked = new LinkedList<int>(days);
var result = new List<int>();
var current = linked.Find(startDay);
result.Add(current.Value);

var finished = false;
while (!finished){
    current = current.Next ?? current.List.First;
    result.Add(current.Value);
    
    if (current.Value == endDay)
    {
        finished = true;
    }
}

Obviously you would have to implement all the protection against null values etc. But concept would work as you like

CodePudding user response:

You can return all items twice i.e.

{0, 1, 2, 3, 4, 5, 6} -> 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6

And then use good old Linq:

List<int> days = new List<int> { 0, 1, 2, 3, 4, 5, 6 };

int startDay = 6;
int endDay = 4;

...

var result = days
  .Concat(days) // <- Repeats days twice
  .SkipWhile(day => day != startDay)
  .TakeWhile(day => day != endDay)  
  .Append(endDay)
  .ToList();

CodePudding user response:

I would use this simple method using Enumerable.Range and Prepend:

public static IEnumerable<int> GetRange(int startValue, int endValue, int zero = 0)
{
    if (startValue < endValue)
    {
        return Enumerable.Range(startValue, endValue - startValue   1);
    }
    
    return Enumerable.Range(zeroValue, endValue - zero   1).Prepend(startValue);
}

int startValue = 6;
int endValue = 4;
List<int> resultList = GetRange(startValue, endValue).ToList(); 
  • Related