Reputation: 59
How do I convert following foreach loop into linq equivalent? Also the foreach loop or linq performs better? The number of items here are only limited, may be in 100s. Thanks in advance.
ObservableCollection<ListItem> _ListItems = null;
string[] listItems = ListValueString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var lstItem in listItems)
{
var itm = new ListItem();
string[] listTexts = lstItem.Split(':');
itm.ListText = listTexts[0];
itm.ListId = Int32.Parse(listTexts[1]);
itm.IsActive = true;
if (_defaultString == Int32.Parse(listTexts[1]))
{
itm.IsInUse = true;
}
_ListItems.Add(itm);
}
Upvotes: 2
Views: 1014
Reputation: 460238
You can use this query that uses an anonymous type to store intermediate results:
List<ListItem> items = ListValueString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(lstItem => new { lstItem, listTexts = lstItem.Split(':') })
.Select(x => new ListItem()
{
ListText = x.listTexts[0],
ListId = Int32.Parse(x.listTexts[1]),
IsActive = true,
IsInUse = Int32.Parse(x.listTexts[1]) == _defaultString
})
.ToList();
var _ListItems = new ObservableCollection<ListItem>(items);
LINQ also uses loops so there will be no noticeable performance difference.
Upvotes: 1