How to select decreasing sub-series with Linq - linq

I have a list of prices ordered by date. I need to select all monotonously decreasing values. The following code works:
public static List<DataPoint> SelectDecreasingValues(List<DataPoint> dataPoints)
{
var ret = new List<DataPoint>(dataPoints.Count);
var previousPrice = dataPoints[0].Price;
for (int i = 0; i < dataPoints.Count; i++)
{
if (dataPoints[i].Price <= previousPrice)
{
ret.Add(dataPoints[i]);
previousPrice = dataPoints[i].Price;
}
}
return ret;
}
However, is there a shorter/cleaner way to accomplish it with Linq?

This code is equivalent:
previousPrice = dataPoints[0].Price;
var ret = dataPoints.Where(x => {
if(x.Price <= previousPrice)
{ previousPrice = x.Price; return true;}
return false;
}).ToList();
However, if you don't need to have a list, go with plain enumerables and drop the ToList at the end. That way you can make use of the deferred execution feature built into LINQ.
The following code is also equivalent:
DataPoint previous = dataPoints.FirstOrDefault();
var ret = dataPoints.Where(x => x.Price <= previous.Price)
.Select(x => previous = x).ToList();
This works because of the deferred execution in LINQ. For each item in dataPoints it will first execute the Where part and then the Select part and only then will it move to the second item in dataPoints.
You need to decide which version you want to use. The second one is not as intention revealing as the first one, because you need to know about the internal workings of LINQ.

public IEnumerable<T> WhereMonotonicDecreasing<T>(
IEnumerable<T> source,
Func<T, IComparable> keySelector)
{
IComparable key;
bool first = true;
foreach(T t in source)
{
if (first)
{
key = keySelector(t);
yield return t;
first = false;
}
else
{
IComparable newKey = keySelector(t);
if (newKey.CompareTo(key) < 0)
{
key = newKey;
yield return t;
}
}
}
}
Called by:
dataPoints.WhereMonotonicDecreasing(x => x.Price);

previousPrice = dataPoints[0];
dataPoints.Where(p => p.Price <= previousPrice.Price)
.Select(p => previousPrice = p);
You can then use .ToList() if you really need one.

How about (untested):
return dataPoints.Take(1)
.Concat(dataPoints.Skip(1)
.Zip(dataPoints,
(next, previous) =>
new { Next = next, Previous = previous })
.Where(a => a.Next.Price <= a.Previous.Price)
.Select(a => a.Next))
.ToList();
Essentially, this overlays a "one-deferred" version of the sequence over the sequence to produce "next, previous" tuples and then applies the relevant filters on those tuples. The Take(1) is to pick the first item of the sequence, which it appears you always want.
If you don't care for the readability of the variable names, you could shorten it to:
return dataPoints.Take(1)
.Concat(dataPoints.Skip(1)
.Zip(dataPoints, Tuple.Create)
.Where(a => a.Item1.Price <= a.Item2.Price)
.Select(a => a.Item1))
.ToList();

Related

Code Rewite for tuple and if else statements by using LINQ

In my C# application i am using linq. I need a help what is the syntax for if-elseif- using linq in single line. Data, RangeDate are the inputs. Here is the code:
var Date1 = RangeData.ToList();
int record =0;
foreach (var tr in Date1)
{
int id =0;
if (tr.Item1 != null && tr.Item1.port != null)
{
id = tr.Item1.port.id;
}
else if (tr.Item2 != null && tr.Item2.port != null)
{
id = tr.Item2.port.id;
}
if (id >0)
{
if(Data.Trygetvalue(id, out cdat)
{
// Do some operation. (var cdata = SumData(id, tr.item2.port.Date)
record ++;
}
}
}
I think your code example is false, your record variable is initialized to 0 on each loop so increment it is useless .
I suppose that you want to count records in your list which have an id, you can achieve this with one single Count() :
var record = Date1.Count(o => (o.Item1?.port?.id ?? o.Item2?.port?.id) > 0);
You can use following code:
var count = RangeData.Select(x => new { Id = x.Item1?.port?.id ?? x.Item2?.port?.id ?? 0, Item = x })
.Count(x =>
{
int? cdate = null; // change int to your desired type over here
if (x.Id > 0 && Data.Trygetvalue(x.Id, out cdat))
{
// Do some operation. (var cdata = SumData(x.Id, x.Item.Item2.port.Date)
return true;
}
return false;
});
Edit:
#D Stanley is completely right, LINQ is wrong tool over here. You can refactor few bits of your code though:
var Date1 = RangeData.ToList();
int record =0;
foreach (var tr in Date1)
{
int? cdat = null; // change int to your desired type over here
int id = tr.Item1?.port?.id ?? tr.Item2?.port?.id ?? 0;
if (id >0 && Data.Trygetvalue(id, out cdat))
{
// Do some operation. (var cdata = SumData(id, tr.Item2.port.Date)
record ++;
}
}
Linq is not the right tool here. Linq is for converting or querying a collection. You are looping over a collection and "doing some operation". Depending on what that operation is, trying to shoehorn it into a Linq statement will be harder to understand to an outside reader, difficult to debug, and hard to maintain.
There is absolutely nothing wrong with the loop that you have. As you can tell from the other answers, it's difficult to wedge all of the information you have into a "single-line" statement just to use Linq.

LINQ with list<int> quering the Value of a Dictonary<int, object>

I have a problem with a query. I have a List with int and want to use it to get the values from my dictionary. The dictionary-keys are int and some of them have the value of the list-items. My question is how i get the objects out of the dictionary, thats keys matces the list items. Was programming JAVA the last years and now struggling with LINQ :(
Thanks in advance
Problem solved. Thank you all :)
No idea how to close this topic. I am reading stackoverflow since one year, but this was my first post.
You can use Linq to join list items with dictionary KeyValuePair entries on entry key. And then select entry value from each joined pair:
var values = from l in list
join kvp in dictionary on l equals kvp.Key
select kvp.Value;
Lambda syntax:
var values = list.Join(dictionary, l => l, kvp => kvp.Key, (l,kvp) => kvp.Value);
Basically:
var value = dictionary[integerKey];
Or:
if (dictionary.TryGetValue(integerKey, out value)) {
}
You can also create an extension method:
public static class DictionaryExtensions
{
public static IEnumerable<TValue> FilterValuesBy<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IEnumerable<TKey> filter)
{
if (dictionary == null) throw new ArgumentNullException("dictionary");
if (filter == null) throw new ArgumentNullException("filter");
var coll = filter as ICollection<TKey> ?? new HashSet<TKey>(filter);
return dictionary.Where(kvp => coll.Contains(kvp.Key)).Select(kvp => kvp.Value);
}
}
Usage:
class Program
{
static void Main()
{
var dict = Enumerable.Range(0, 10).ToDictionary(x => x);
var filter = Enumerable.Range(0, 2);
foreach (var i in dict.FilterValuesBy(filter))
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
Simple Linq method chain:
var dict = Enumerable.Range(0, 10).ToDictionary(x => x);
var filter = Enumerable.Range(0, 2).ToList();
var filtered = dict.Where(x => filter.Contains(x.Key)).Select(x => x.Value).ToList();

Set the list value using linq

Hi I want to set the value in the list of objects that matches the given condition in the where clause.Is it possible?
Other work around is to get the list of objects using where clause and then iterate using for Or foreach loop and update the value.
listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest);
I have list listOfRequestAssigned of objects and want to update some propery of the objects that match my search criteria.
class Request
{
bool _requestCompleted;
int _requestedNumber;
public int RequestedNumber
{
get { return _requestedNumber; }
set { _requestedNumber = value; }
}
public bool RequestCompleted
{
get { return _requestCompleted; }
set { _requestCompleted = value; }
}
}
I want to update RequestCompleted property of all objects that match criteria using Linq
You can use ForEach in Linq
listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest).ToList().ForEach(x => x.RequestCompleted = true);
if you have more than one update to do,
listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest).ToList().ForEach(x => { x.RequestCompleted = true; x.OtherProperty = value; } );
Where(...) give you a query, not a Request or a List<Request>. Use FirstOrDefault() if you want to have one (or 0) result, or ToList() if you want to have a list of results on wich you can use ForEach().
In general Linq is a query- not an update tool, but you can use a foreach:
var currentRequests = listOfRequestAssigned
.Where(x => x.RequestedNumber == CurrentRequest);
foreach(var req in currentRequests)
{
req.RequestCompleted = true;
}
Since you have specific collection of type List, you can just use ForEach and a conditional set:
listOfRequestAssigned.Foreach(x => { if (x.RequestedNumber == CurrentRequest) x.RequestCompleted = true;}});
If you had a more generic collection IEnumerable, you can use Select in Linq to build a projection where property will be set as desired (original collection will be left untouched!):
listOfRequestAssigned
.Where(x => x.RequestedNumber == CurrentRequest)
.Select(x => { x.RequestCompleted = true; return x; })
You can use to assign boolean value by following on comparing time. This is the very simplest and smart way for bool property.
listOfRequestAssigned.ForEach(x => x.RequestCompleted = x.RequestedNumber
== CurrentRequest);

EF Code First selecting rows based on many to many relationship

I have the following code in my repository:
public PagedResult<Post> GetAllPublishedByTag(int tagId, int start, int max)
{
var query = Database.Set<Post>().Where(p => p.IsPublished)
.OrderByDescending(p => p.CreatedAt)
.Skip(start)
.Take(max);
int total = query.Count();
var result = query.ToList();
return new PagedResult<Post>(result, total);
}
This will give me all published posts. But what I want is selecting all published posts for a certain tag. My model is setup in such a way that tags have a many to many relationship to posts. I tried to slightly modify the above code but this did not work:
public PagedResult<Post> GetAllPublishedByTag(Tag tag, int start, int max)
{
var query = Database.Set<Post>().Where(p => p.Tags.Contains(tag) && p.IsPublished)
.OrderByDescending(p => p.CreatedAt)
.Skip(start)
.Take(max);
int total = query.Count();
var result = query.ToList();
return new PagedResult<Post>(result, total);
}
I would prefer to pass in the tagId (as per the first code example) as opposed to the tag object but not sure how to correctly write the LINQ statement.
var query = Database.Set<Post>().Where(p => p.Tags.Any(t => t.Id == tagId) && p.IsPublished)
.OrderByDescending(p => p.CreatedAt)
.Skip(start)
.Take(max);
Side Note: I believe you may have issues with your pagination, as the variable total is calculated after skip/take are called.

LINQ to Entites/IQueryable: Sorting on multiple fields

I have the following that I'd like to sort:
IQueryable<Map> list;
list = from item in ctx.MAP
.Include("C")
.Include("L")
.Include("L.DP")
select item;
return list.OrderBy(m=>(m.L.DP.Name + m.L.Code));
This works, but it sorts alphabetically - so 12 comes before 9. (Assume Code is a numeric field)
What is the best way to sort this so Code is sorted numerically?
You probably want to use the ThenBy extension method to be able to sort by multiple fields ;)
In your case that would be
return list.OrderBy(m=>m.L.DP.Name).ThenBy(m => m.L.Code);
var results = db.Blogs.AsEnumerable()
.Select(sr => new
{
Searchresult = sr,
Words = Regex.Split(sr.Name, #"[^\S\r\n {1,}").Union(Regex.Split(sr.Name2, #"[^\S\r\n]{1,}"))
})
.OrderByDescending(x => x.Words.Count(w => {
foreach (var item in searchTerms)
{
if(w.ToLower().Contains(item))
{
return true;
}
}
return false;
}))
.Select(x => x.Searchresult);

Resources