c# method with List / param int[] parameters - c#

I have to make method called CalculateBill with given parameters, but I cannot define how to connect those two parameters inside of code.
public class Bill {
public int CalculateBill (List<Item> itemList, params int[] items) {
// Need to write code here
//itemList : available items in the shop
// int[] items : array of ItemId's purchased by customer
// A customer can buy same item many times , so itemId can be repeated in items array
// return sum of al items prices
}
}
The item class is like
public class Item {
public int ItemId {get; set;}
public int ItemPrice { get; set; }
}
The Program Class is like
List<Item> itemList = new List<Item> {
new Item() {ItemId = 100 , ItemPrice = 50},
new Item() {ItemId = 101 , ItemPrice = 60},
new Item() {ItemId = 102 , ItemPrice = 20},
};
Bill bObj = new Bill();
int a = bObj.CalculateBill(itemList, 101, 102, 101);
int b = bObj.CalculateBill(itemList);

It sounds like you need help implementing the CalculateBill function using your existing architecture. I would implement it like below.
I renamed your 'itemList' parameter to 'itemsInShop' and I also renamed your 'items' parameter to 'itemsPurchasedIDs'. Always try to make your variable names as descriptive as possible to make it easy to understand and read.
public int CalculateBill(List<Item> itemsInShop, params int[] itemsPurchasedIDs)
{
int totalSpent = 0;
for (int i = 0; i < itemsPurchasedIDs.Length; i++)
{
int itemId = itemsPurchasedIDs[i];
for (int j = 0; j < itemsInShop.Count; j++)
{
var shopItem = itemsInShop[j];
if (shopItem.ItemId == itemId)
{
totalSpent += shopItem.ItemPrice;
break;
}
}
}
return totalSpent;
}

You are almost there. Create a class for the shop that contains the items available so you don't need to pass it as an argument.
Also, since you want to retrieve Items with id values, you need a Dictionary<int,Item> which would allow you to do this quickly.
Here is the Shop class with a dictionary
public class Shop
{
private readonly Dictionary<int, Item> _items;
public Shop()
{
_items = new Dictionary<int, Item>();
}
public IReadOnlyList<Item> Items { get => _items.Values.ToList(); }
public void Add(Item item) => _items.Add(item.ItemId, item);
public Item[] GetItems(params int[] idList)
{
List<Item> list = new List<Item>();
foreach (var id in idList)
{
list.Add(_items[id]);
}
return list.ToArray();
}
public decimal CalculateBill(params int[] idList)
{
var items = GetItems(idList);
decimal sum = 0m;
foreach (var item in items)
{
sum += item.ItemPrice;
}
return sum;
}
}
Otherwise, you would need to lookup the items one by one. Here is a solution that uses theList.Find() method to match the Item from the id.
public class Shop
{
private readonly List<Item> _items;
public Shop()
{
_items = new List<Item>();
}
public IReadOnlyList<Item> Items { get => _items.ToList(); }
public void Add(Item item) => _items.Add(item);
public Item[] GetItems(params int[] idList)
{
List<Item> list = new List<Item>();
foreach (var id in idList)
{
list.Add(_items.Find((item)=>item.ItemId==id));
}
return list.ToArray();
}
public decimal CalculateBill(params int[] idList)
{
var items = GetItems(idList);
decimal sum = 0m;
foreach (var item in items)
{
sum += item.ItemPrice;
}
return sum;
}
}

Here are three alternatives for you to try:
public int CalculateBill(List<Item> itemsInShop, params int[] itemsPurchasedIDs) =>
itemsPurchasedIDs
.Join(itemsInShop, id => id, item => item.ItemId, (_, item) => item.ItemPrice)
.Sum();
public int CalculateBill2(List<Item> itemsInShop, params int[] itemsPurchasedIDs) =>
(
from id in itemsPurchasedIDs
join item in itemsInShop on id equals item.ItemId
select item.ItemPrice
).Sum();
public int CalculateBill3(List<Item> itemsInShop, params int[] itemsPurchasedIDs)
{
var map = itemsInShop.ToDictionary(x => x.ItemId, x => x.ItemPrice);
return itemsPurchasedIDs.Sum(x => map[x]);
}

Related

GroupBy with linq entity poco

I have this entities
public class Counter
{
public int DocEntry { get; set; }
public int LineId { get; set; }
public string Item { get; set; }
public decimal Quantity { get; set; }
public string FromWarehouse { get; set; }
public string ToWarehouse { get; set; }
public virtual List<Batch> batchs { get; set; }
}
public class Batch
{
public string BatchNumber { get; set; }
public decimal Quantity { get; set; }
}
And I have List count,I should group the elements of the list based on the Item value, FromWarehouse, ToWarehouse, and the result should be grouped with summed quantity and the list of Batch merged, I tried cycling the Counter list using the foreach method and inserting in a new list the first element, in the subsequent iterations if the current row reflected the values of the one already in the list I summarized the quantities and added to the Batch list the elements of the Batch list of the i-th line, otherwise I added a new line, this approach I it seemed too complicated, not being very expert on linq or in any case is there an easier way to manage the group by?
This is my method:
public static List<Counter> GroupBy(List<Counter> list)
{
List<Counter> rows = new List<Counter>();
int i = 0;
foreach (Counter elem in list)
{
if (list.First() == elem)
{
rows.Add(elem);
i++;
}
else
{
if (elem.Item == rows.ElementAt(i).Item &&
elem.FromWarehouse == rows.ElementAt(i).FromWarehouse &&
elem.ToWarehouse == rows.ElementAt(i).ToWarehouse)
{
rows.First().Quantity += elem.Quantity;
rows.First().batchs.Add(elem.batchs.First());
}
else
{
rows.Add(elem);
i++;
}
}
}
return rows;
}
This is the solution:
public static List<Counter> GroupBy(List<Counter> list)
{
List<Counter> rows = new List<Counter>();
foreach (Counter elem in list)
{
if (rows.Any(x=>x.Item == elem.Item &&
x.FromWarehouse == elem.FromWarehouse &&
x.ToWarehouse == elem.ToWarehouse))
{
rows.First().Quantity += elem.Quantity;
rows.First().batchs.Add(elem.batchs.First());
}
else
{
rows.Add(elem);
}
}
return rows;
}
Let's try to write the Linq, step by step.
"I have List count":
List<Counter> count = ...
"I should group the elements of the list based on the Item value, FromWarehouse, ToWarehouse":
var result = count
.GroupBy(item => new {
item.Item,
item.FromWarehouse
item.ToWarehouse
})
"result should be grouped with summed quantity and the list of Batch merged", i.e. you should Aggregate items within each chunk
var result = count
.GroupBy(item => new {
item.Item,
item.FromWarehouse
item.ToWarehouse
})
.Select(chunk => new {
key = chunk.Key,
summary = chunk.Aggregate(
Tuple.Create(0m, new List<Batch>()), // initial empty
(s, a) => Tuple.Create(s.Item1 + a.Quantity, // add
s.Item2.Concat(a.batchs).ToList()) // merge
})
Finally, let's represent the result in more convenient (readable) format:
var result = count
.GroupBy(item => new {
item.Item,
item.FromWarehouse
item.ToWarehouse
})
.Select(chunk => new {
key = chunk.Key,
summary = chunk.Aggregate(
Tuple.Create(0m, new List<Batch>()),
(s, a) => Tuple.Create(s.Item1 + a.Quantity,
s.Item2.Concat(a.batchs).ToList())
})
.Select(item => new {
Item = item.key.Item,
FromWarehouse = item.key.FromWarehouse,
ToWarehouse = item.key.ToWarehouse,
Quantity = item.summary.Item1,
Batches = item.summary.Item2
}); // Add ToArray() if you want to materialize

Sorting list of objects by NextObjectId

I have list of objects that have properties Id and NextObjectId. NextObjectId is referring to Id of another object telling to that object it is supposed to be after the object it's referring to. Object Ids are random and not in any particular order.
Can you show the most efficient way how to organize list of objects from random order to ascending according to NextObjectId?
If I understand you in the correct way, you have the following relation:
A.Id = B.NextObjectId && B.Id != A.Id.
So you need to sort by Id with Linq.
IEnumerable<AClass> orderedObjects = objects.OrderBy(e => e.Id);
Or if you want to sort by NextObjectId
IEnumerable<AClass> orderedObjects = objects.OrderBy(e => e.NextObjectId);
I made this algorithm. It should do what you wanted to:
class Program
{
private static Random random = new Random();
static void Main(string[] args)
{
//GENERATE A RANDOM LIST FOR THE EXAMPLE
List<Item> items = new List<Item>();
int? lastID = null;
for(int i = 0; i < 100; i++)
{
int id = random.Next();
items.Add(new Item() { ID = id, NextItemID = lastID });
lastID = id;
}
//GENERATE A RANDOM LIST FOR THE EXAMPLE
items = items.OrderBy(x => random.Next()).ToList(); //SHUFFLE THE LIST FOR THE EXAMPLE
items.OrderByNextItemID(); //SORT THE LIST BY NextItemID
}
}
public static class Extensions
{
public static void OrderByNextItemID(this List<Item> items)
{
List<Item> results = new List<Item>();
Item item = items.Where(x => x.NextItemID == null).First();
results.Add(item);
items.Remove(item);
int length = items.Count;
for(int i = 0; i < length; i++)
{
item = items.Where(x => x.NextItemID == results.Last().ID).FirstOrDefault();
if(item != null)
{
results.Add(item);
items.Remove(item);
}
}
results.Reverse();
items.AddRange(results);
}
}
public class Item
{
public int ID { get; set; }
public int? NextItemID { get; set; }
}
Here it is.
If I understood you right, you have a class like this:
public class MyObject
{
public int Id { get; set; }
public int? NextObjectId { get; set; }
}
and List<MyObject> like this one:
List<MyObject> myObjects = new List<MyObject>
{
new MyObject {Id = 5, NextObjectId = 4},//4
new MyObject {Id = 4, NextObjectId = 1},//5
new MyObject {Id = 2, NextObjectId = 87},//1
new MyObject {Id = 70, NextObjectId = 5},//3
new MyObject {Id = 1, NextObjectId = null},//6
new MyObject {Id = 87, NextObjectId = 70}//2
};
Since the NextObjectId refers to the next object's Id, then there must be a NextObjectId with null (or zero), that is the last element, and the item before it is the before last element which its NextObjectId's value equals to the last element's Id. We can build the method OrderChain on this algorithm:
private static IEnumerable<MyObject> OrderChain(List<MyObject> myObjects)
{
var starter = myObjects.FirstOrDefault(x => x.NextObjectId == null);
yield return starter;
var count = myObjects.Count;
while (count > 1)
{
yield return GetCurrent(myObjects, ref starter);
count--;
}
}
private static MyObject GetCurrent(List<MyObject> lst, ref MyObject current)
{
var id = current.Id;
current = lst.SingleOrDefault(x => x.NextObjectId == id);
return current;
}
Then you can sort it like this:
var myOrderedObjects = OrderChain(myObjects).Reverse().ToList();
this gives me this list:
{ Id = 2, NextObjectId = 87 },//1
{ Id = 87, NextObjectId = 70 },//2
{ Id = 70, NextObjectId = 5 },//3
{ Id = 5, NextObjectId = 4 },//4
{ Id = 4, NextObjectId = 1 },//5
{ Id = 1, NextObjectId = null }//6
I'd simply create a dictionary from its object ID to the object. From there, assuming you have a starting object and some way of finishing (e.g. a NextObjectId of null) you can just build the list up. It's not particularly LINQ-based, but it is simple:
YourType item = ...; // Whatever should come first.
var map = objects.ToDictionary(obj => obj.ObjectId);
var list = new List<YourType>();
list.Add(item);
while (item.NextObjectId != null)
{
// TODO: Handle missing objects? (Use TryGetValue instead of the indexer)
item = map[item.NextObjectId];
list.Add(item);
}

C# Dictionary Calculate sum of group values

I'm currently working on an application in C#. Imagine a store front with a checkout. I have a dictionary structure with an object as Key, and an int object counter as value.
the structure looks like this:
Dictionary<myObject, int> items.
The basic idea is, to pass a dictionary of Items into a method. I'm only adding unique myObjects to the dictionary. The myObject has a counter rule attached. Once the counter rule is full filled I want to do a calculation with all myObects in the dictionary.
The myObject looks like this:
public class myObject
{
string ItemId { get; set; }
Discount Discount { get; set; }
}
public class Discount
{
public int Count { get; set; }
public decimal Price { get; set; }
public IDiscountHandler DiscountHandler => new DiscountHandler();
}
A sample myObject could look like this:
var myObectA = new myObject()
{
ItemId = "A"
};
var discountA = new Discount()
{
Count = 2,
Price = 12 // special price, if 2 myObjects were added to the Dictionary
};
myObjectA.Discount = discountA;
1) I fill the items Dictionary and pass it to the Handler method:
private decimal _totalDiscountedValue { get; set; } = 0;
if (!_items.ContainsKey(myObject))
{
_items.Add(myObject, 1);
}
else
{
_items[myObject]++;
}
_totalDiscountedValue += _discountHandler.CalculateDiscount(_items);
2) In my Handler I try to sum up all the discount values, once a counter rule is full filled. But here I'm struggling unfortunately:
public class DiscountHandler : DiscountHandler
{
private decimal _totalDiscount { get; set; } = 0;
public override decimal CalculateDiscount(IDictionary<myObject, int> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
// I'm struggeling here:
// check if Dictionary[i].Dicount.Count = Dictionary.Value
// then _totalDiscount += Dictionary[i].Discount.Price
return _totalDiscount;
}
}
Do you know how to solve this issue, or do you have an idea on how to possibly solve this?
Thank you very much !!
You could just iterate through the Dictionary using foreach as follows:
public override decimal CalculateDiscount(IDictionary<myObject, int> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
foreach (var kvp in items)
{
if (kvp.Key.Discount.Count == kvp.Value)
_totalDiscount += kvp.Key.Discount.Price;
}
return _totalDiscount;
}
Using Linq
//check if yourDictonary is not null
var sum = yourDictonary.Select(x => x.Key.Discount.Count == x.Value).Sum(x => x.Value)
IF I understood the problem properly, maybe doing this would work
foreach (var item in items)
{
if (item.Key.Discount.Count == item.Value)
_totalDiscount += item.Key.Discount.Price;
}
return __totalDiscount;

How to group only subsequent items with the same property using linq

I have input that could look like this:
A 1 2 C,D
A 2 3 C,E
B 4 5 F
A 6 7
A 7 8 D
A 9 10 E
I store this in my model class:
public class Item {
public String Name {get;set;}
public int Start {get;set;}
public int End {get;set;}
public List<string> Orders {get;set;}
}
I tried to use Linq to merge all subsequent items if the items have the same name and generate a new item that has the start value of the first item in the group, the end value of the last item in the group and a union of all order lists. It should then look like this:
A 1 3 C,D,E
B 4 5 F
A 6 10 D, E
I tried the following Linq statement, however, it groups all As and Bs together, independent of whether there are any other items in between. What do I need to change? The union of the order list is also missing.
var groups = items.GroupBy(i => i.Name).ToList();
foreach (var group in groups)
{
result.Add(new Item {
Start = group.First().Start,
End = group.Last().End,
Name = group.First().Name });
}
Use a classic loop for this:
var List<List<Item>> groups = new List<List<Item>>()
var currentGroup = new List<Item> { items.First() };
int i = 0;
foreach(var item in items.Skip(1))
{
if(currentGroup.First().Name != item.Name)
{
groups.Add(currentGroup);
currentGroup = new List<Item> { item };
}
else
{
currentGroup.Add(item);
if(i == items.Count - 2)
groups.Add(currentGroup);
}
i++;
}
Now you can continue with your code by iterating the groups-list.
Maybe not the best or fastest way but I got bored:
int groupID = -1;
var result = items.Select((item, index) =>
{
if (index == 0 || items[index - 1].Name != item.Name)
++groupID;
return new { group = groupID, item = item };
}).GroupBy(item => item.group).Select(group =>
{
Item item = new Item();
var first = group.First().item;
var last = group.Last().item;
item.Name = first.Name;
item.Start = first.Start;
item.End = last.End;
item.Orders = group.SelectMany(g => g.item.Orders).Distinct().ToList();
return item;
});
The variable items should be your input collection like a List<Item>. The result will be stored in result. This is an IEnumerable<Item> but you may add .ToList() or .ToArray() as you like to convert it to List<Item> or Item[].
The result will contain new created items. I did this on purpose to not mess up the input data.
The trick here is to use a local variable as a group id. It is increased if it is the first item or the last item had a different name. Then we group by the group id and the rest of the code will just create the item. The SelectMany method will join all Orders-values from the entire group and Distinct will then remove all duplicates.
This is not done by Linq. I just played a bit using simpler methods. But it gives same result which you wanted.
using System;
using System.Collections.Generic;
public class Item
{
public static List<Item> Database;
static Item()
{
Database = new List<Item>();
}
public Item(string name, int start, int end, params string[] orders)
{
Name = name;
Start = start;
End = end;
Orders = new List<string>();
foreach (string s in orders)
Orders.Add(s);
//putting newly created Item to database
Database.Add(this);
}
//overload for creating tmp Items in GroupThem(), could be done using optinional parameter
public Item(bool AddToDatabase, string name, int start, int end, params string[] orders)
{
Name = name;
Start = start;
End = end;
Orders = new List<string>();
foreach (string s in orders)
Orders.Add(s);
if (AddToDatabase) Database.Add(this);
}
public string Name { get; set; }
public int Start { get; set; }
public int End { get; set; }
public List<string> Orders { get; set; }
public List<Item> GroupedItems()
{
List<Item> groupedItems = new List<Item>();
Item previous = Database[0];
Stack<Item> sameItems = new Stack<Item>();
foreach (Item item in Database)
{
if (previous.Name == item.Name)
{
sameItems.Push(item);
}
else
{
groupedItems.Add(GroupThem(sameItems));
previous = item;
sameItems.Push(item);
}
}
groupedItems.Add(GroupThem(sameItems));
return groupedItems;
}
private Item GroupThem(Stack<Item> sameItems)
{
string newName = "";
int newEnd = 0;
int newStart = int.MaxValue;
List<string> newOrders = new List<string>();
Item tmp = null;
while (sameItems.Count > 0)
{
tmp = sameItems.Pop();
if (tmp.Start < newStart)
newStart = tmp.Start;
if (tmp.End > newEnd)
newEnd = tmp.End;
foreach (string s in tmp.Orders)
if (!newOrders.Contains(s))
newOrders.Add(s);
newName = tmp.Name;
}
return new Item(false, newName, newStart, newEnd, newOrders.ToArray());
}
public override string ToString()
{
string tmp = "";
foreach (string s in Orders)
tmp += " " + s;
return "Name = " + Name + ", Start = " + Start + ", End = " + End +", Orders = "+ tmp;
}
}
class Program
{
static void Main(string[] args)
{
Item item1 = new Item("A", 1, 2, "C", "D");
Item item2 = new Item("A", 2, 3, "C", "E");
Item item3 = new Item("B", 4, 5, "F");
Item item4 = new Item("A", 6, 7);
Item item5 = new Item("A", 7, 8, "D");
Item item6 = new Item("A", 9, 10, "E");
foreach (Item item in item1.GroupedItems())
{
Console.WriteLine(item);
}
}
}
A bit late, I know, but I think the following solution will still help someone.
It includes the original Item class, enhanced with:
A ToString method to simplify inspection.
A CreateSamples method to generate the sample items.
A bonus nested class ComparerByStartAndEnd to sort items based on Start and End properties.
The solution resides in the EXTENSIONS.GroupWhenChanging method and the Item.FromGroup method.
The TEST class provides code to verify everything works as expected.
The actual grouping logic (EXTENSIONS.GroupWhenChanging) simply implements an enumerator that does not invoke Linq methods and allocates only a List object for each group, thus saving both in performance and memory resources.
The method is generic and accepts a comparison predicate, so it is not restricted to the sample Item class.
The creation of the result items, representing the groups with merged orders, is kept in the separate method Item.FromGroup. It uses some Linq to ease the task.
The TEST.Test method does the following:
Creates the list of samples.
Ensures the samples are ordered based on Start and End.
Enumerates the groups (by means of GroupWhenChanging) and creates the corresponing items (through Item.FromGroup).
The Item class:
public static class MODEL
{
public class Item
{
public String Name { get; set; }
public int Start { get; set; }
public int End { get; set; }
public List<string> Orders { get; set; }
/// <inheritdoc/>
public override string ToString()
{
return string.Format("{0} {1} .. {2} {3}", this.Name, this.Start, this.End, string.Join(",", this.Orders));
}
public static Item? FromGroup(IEnumerable<Item> group)
{
var array = group as Item[] ?? group.ToArray();
if (array.Length > 0)
{
var newName = array[0].Name;
var newStart = array.Min(item => item.Start);
var newEnd = array.Max(item => item.End);
var newOrders = array.SelectMany(item => item.Orders).Distinct().OrderBy(orderID => orderID).ToList();
var newItem = new Item()
{
Name = newName,
Start = newStart,
End = newEnd,
Orders = newOrders
};
return newItem;
}
return null;
}
public static IEnumerable<Item> CreateSamples()
{
yield return new Item() { Name = "A", Start = 1, End = 2, Orders = new List<string>() { "C", "D" } };
yield return new Item() { Name = "A", Start = 2, End = 3, Orders = new List<string>() { "C", "E" } };
yield return new Item() { Name = "B", Start = 4, End = 5, Orders = new List<string>() { "F" } };
yield return new Item() { Name = "A", Start = 6, End = 7, Orders = new List<string>() };
yield return new Item() { Name = "A", Start = 7, End = 8, Orders = new List<string>() { "D" } };
yield return new Item() { Name = "A", Start = 9, End = 10, Orders = new List<string>() { "E" } };
}
public sealed class ComparerByStartAndEnd : Comparer<Item>
{
/// <inheritdoc/>
public override int Compare(Item x, Item y)
{
if (x == y)
return 0;
return x.End.CompareTo(y.Start);
}
}
}
}
The EXTENSIONS class:
public static class EXTENSIONS
{
public static IEnumerable<IEnumerable<T>> GroupWhenChanging<T>(this IEnumerable<T> items, Func<T, T, bool> predicate)
{
List<T> group = null;
foreach (var item in items)
{
if (group is null)
group = new List<T>() { item };
else if (predicate(group[group.Count - 1], item))
group.Add(item);
else
{
yield return group;
group = new List<T>() { item };
}
}
if (group is not null)
yield return group;
}
}
The TEST class:
public static class TEST
{
public static void Test()
{
var items = MODEL.Item.CreateSamples().ToList();
items.Sort(new MODEL.Item.ComparerByStartAndEnd());
var groups = items
.GroupWhenChanging((prev, next) => prev.Name == next.Name)
.Select(MODEL.Item.FromGroup)
.ToList();
}
}

C# how to sort list<T> and update to listview, the listview only show part

public class ListKeywords
{
public int ID { set; get; }
public string Keyword { set; get; }
public string Language { set; get; }
public int WordCount { set; get; }
}
List<ListKeywords> keywordsList = new List<ListKeywords>();
//
listview1.Add(new ListKeywords() { ID = keywordsList.Count+1, Keyword = line.Trim(), WordCount = countWords(line) });
i want to add 10000 ListKeywords item to ListKeywords, but i just want to display top 1000 item in listview1 control.
Now, if sort listview1 i want to sort all the item (ListKeywords ), not only sort top 1000 item in listview1.
How to do it ?
Sorry my English is not very good
List<ListKeywords> SortedList = SortedList.OrderBy(o=>o.ID).Take(1000).ToList();
You could just bind your listview to a property that does the work for you. Something like:
public List<ListKeywords> Top1000Sorted
{
get
{
return keywordsList.OrderBy(x => x.ID).Take(1000).ToList();
}
}
And bind the ListView using:
listview1.ItemsSource = Top1000Sorted;
If you want to sort by keywrods then use this:
var top1000Items = keywordsList.OrderByDescending(x=>x.Keyword).Take(1000);
If you want to sord by ID then use this:
var top1000Items = keywordsList.OrderByDescending(x=>x.ID).Take(1000);
So if you have 10.000 items and and tier IDs start from 1 and finish to 10000, then if you sort by ID, the top1000Items would have Ids ranging from 9001 to 10000.
Just use lists's OrderBy method prior to selecting the top 1000 objects. Then Take the top 1000 entries.
So, something like this method:
public List<ListKeywords> SortByIdAndSelectRange(List<ListKeywords> list, int range)
{
return list.OrderBy(x => x.ID).Take(range).ToList();
}
Use:
myList = SortAndSelectRange(myList, 1000);
You can modify that method further to decide what you want to sort by.
Here's a very crude sample showing the use of the above method:
class ListKeywords
{
public int ID { set; get; }
}
class Program
{
static void Main(string[] args)
{
var myList = new List<ListKeywords>();
Random rnd = new Random();
for (int i = 0; i < 3000; i++)
{
var entry = new ListKeywords() { ID = rnd.Next(3000, 9999) };
myList.Add(entry);
}
myList = SortByIdAndReturnRange(myList, 1000);
foreach (var entry in myList)
{
Console.WriteLine(entry.ID);
}
}
static List<ListKeywords> SortByIdAndReturnRange(List<ListKeywords> list, int range)
{
return list.OrderBy(x => x.ID).Take(range).ToList();
}
}
Lastly, you can stack sorting:
myList.OrderBy(x => x.Param1).ThenBy(x => x.Param2).ThenBy(x => x.Param3) ... and so on.
I use that when I want to sort a list by date, and then every day to be sorted by time.

Categories

Resources