I am new to C# language, I have started learning LINQ in that
So I just want to convert the code using linq. Is there any way to do. The current implementation is not a stylish one.
var list = new List<int>();
for (int index = 0; index < contentList.Count; index++)
{
list.Add(MyClass.GetCorrespondence(module, index));
}
return list;
You could write it like this:
var list = contentList.Select((_, i) => MyClass.GetCorrespondence(module, i)).ToList();
or like this
var list = Enumerable.Range(0,contentList.Count).Select(i => MyClass.GetCorrespondence(module, i)).ToList();
But, honestly, dont do either! Your code is perfectly readable as it is.
If you must use LINQ for this then you can use the overload for Select which "projects each element of a sequence into a new form by incorporating the element's index." e.g:
list.AddRange(contentList.Select((c, index) => MyClass.GetCorrespondence(c, index));
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8
this method work:
var result= contentList.Select((paramter,index)=>MyClass.GetCorrespondence(module,index)).ToList();
If you're desperate to do it with Linq then you could try:
list.AddRange(Enumerable.Range(0, contentList.Count).Select(index => MyClass.GetCorrespondence(module, index)))
or:
list = Enumerable.Range(0, contentList.Count).Select(index => MyClass.GetCorrespondence(module, index)).ToList();
You could also use the ForEach LINQ statement.
contentList.ForEach(x => list.Add(MyClass.GetCorrespondence(module, x)));
EDIT: Any reason why this was down voted?
Related
I currently have:
List<TimeSpan> times = new List<TimeSpan>();
// ... setup the thousands of times ...
string[] timeStrings = new string[times.Count];
for (int i = 0; i < times.Count; i++)
timeStrings[i] = times[i].ToString("mm.ss");
I feel like there should be an easy way to do this in LINQ, but I can't find it. I got close with times.Select(s => s.ToString("mm.ss").ToArray()), but it just got the first element.
Side note: Are there any good LINQ tutorials out there?
You almost had it:
var timesAsString = times.Select(s => s.ToString("mm.ss")).ToArray()
var timesAsString = times.Select(t => t.ToString("mm.ss")).ToArray();
Your ToArray call is currently on the string, not the enumerable.
This is basically right, the problem is that your ToArray is being called on the string when it should be outside of that (basically a typo);
What you have;
times.Select(s => s.ToString("mm.ss").ToArray())
what you should have;
times.Select(s => s.ToString("mm.ss")).ToArray();
times.Select(s => s.ToString("mm.ss")).ToArray();
I have the following loop:
for (var i = 0; i < myStringList.Count; i++)
{
myStringList[i] = myStringList[i].ToUpper();
}
into a Linq expression?
Use this
myStringList = myStringList.Select(x => x.ToUpper()).ToList();
I have used .ToList() in the end assuming that myStringList is a List<string>.
FoodforThought: In List there is a method ForEach() which performs an action on each item like this.
myStringList.ForEach(x => x.Foo = Bar);
But that cannot be used here as that method can be used to change a property of an item but cannot be used to change the item itself.
So this will not do anything
myStringList.ForEach(x => x = x.ToUpper());
myStringList = myStringList.Select(x => x.ToUpper()).ToList();
I have read couple of articles on Linq and Func<> and understood simple examples but I cannot able to use them in day to day programming. I am keen to know what are the scenarios the LINQ or lambda expressions useful and should be used
For this code: Can I use Linq or lambda expressions
List<int> abundantNumbers = new List<int>();
for (int i = 0; i < 28888; i++)
{
if (i < pta.SumOfDivisors(i))
{
abundantNumbers.Add(i);
}
}
Yes, you can absolutely use LINQ in your example:
var abundantNumbers = Enumerable.Range(0, 28888)
.Where(i => i < pta.SumOfDivisors(i))
.ToList();
Note that it's important that you didn't just post code which added to list - you posted code which showed that the list was empty to start with. In other words, you're creating a list. If you'd merely had code which added to an existing list, I'd have used something like:
var query = Enumerable.Range(0, 28888).Where(i => i < pta.SumOfDivisors(i));
abundantNumbers.AddRange(query);
If you want to do it with the LINQ notation, it would go like this:
var abundantNumbers = (from i in Enumerable.Range(0, 28888)
where i < pta.SumOfDivisors(i)
select i)
.ToList();
I have a list:
var _books = new List<int> {233,5,20};
And a ListBox with a lot of books (their value is an item id)
How do I take this working code:
var t = from ListItem n in lbBooks.Items
where _books.Contains(int.Parse(n.Value))
select n;
foreach(ListItem i in t)
{
i.Selected = true;
}
and convert it to lambda:
lbBooks.Items.Cast<ListItem>()
.Where(n => _books.Contains(int.Parse(n.Value)))
.Select(n => n.Selected = true);
The best option? Don't. LINQ queries are supposed to be just that – queries. And queries aren't supposed to have side effects. Your approach using foreach is perfectly fine.
If you really wanted, you could create your own extension method ForEach(), similar to the one on List<T>, but I don't think that's a good idea.
Your not far off, you need to return the whole object and set Selected to true. Something like:
lbBooks.Items.Cast<ListItem>()
.Where(n => _books.Contains(int.Parse(n.Value)))
.Select(n => SetSelected(n));
The above .Select can be shortend to .Select(SetSelected); if you prefer
private ListItem SetSelected(ListItem listItem)
{
listItem.Selected = true;
return listItem
}
Additionally to save casting you could utilise the SetSelected to handle your casting once you have just the records you want. Your query would then become:
lbBooks.Items.Where(n => _books.Contains(int.Parse(n.Value)))
.Select(n => SetSelected(n));
private ListItem SetSelected(Item item)
{
ListItem result = item as ListItem;
result.Selected = true;
return result;
}
There is no build in ForEach extension method. You can create your own, but I do not see any problem with the code you have.
Cast to .ToList() and use the `ForEach' operator as so:
lbBooks.Items.Cast<ListItem>()
.Where(n => _books.Contains(int.Parse(n.Value)))
.Select(n => n).ToList().ForEach(n=> n.Selected=true);
I need an easy way to convert a List<int> to a string array.
I have:
var the_list = new List<int>();
the_list.Add(1);
the_list.Add(2);
the_list.Add(3);
string[] the_array = new string[the_list.Count];
for(var i = 0 ; i < the_array.Count; ++i)
the_array[i] = the_list[i].ToString();
...which looks to be very ugly to me.
Is there an easier way?
Note: I'm looking for an easier way - not necessarily a faster way.
Use LINQ:
string[] the_array = the_list.Select(i => i.ToString()).ToArray();
I know you have a good answer, but you don't need LINQ or Select. You can do it with a ConvertAll and an anonymous method. Like this:
var list = new List<int>();
....
var array = list.ConvertAll( x => x.ToString() ).ToArray();
Similar idea, but I think this is not linq. in case that matters.
Sorry, I don't have .NET installed on this machine, so totally untested:
var theList = new List<int>() { 1, 2, 3 };
var theArray = theList.Select(e => e.ToString()).ToArray(); // Lambda Form
var theArray = (from e in theList select e.ToString()).ToArray(); // Query Form
List has a ToArray() method. It will save you typing but probably won't be more efficient.
Because your list only has a number, you can easily convert them to a string. Just create a loop and convert its members to the string.
string[] the_array = new string[the_list.Count];
int i=0;
foreach(var item in the_list)
{
the_array[i] = item.ToString();
i++;
}