Summing up double lists in a Linq GroupBy - c#

I need to group a large number of records which were recorded every minute into daily and bind them to a chart. These records have two fields the datetime value and the double list. I've tried something like this:
var result = Alldatas
.AsEnumerable()
.GroupBy(r => r.TimeStamp.Day)
.Select(x => new {
Day = x.Key,
Value = x.Sum(r => r.Value.Sum())
})
.OrderBy(x => x.Day)
.ToList();
The problem is that the list items in the double list is being summed up each other into a single double value. The correct result is that double lists should be adding up each other into a single double list for each day. Is there a way to achieve this? Thanks.

If I understood you correctly, here is the code:
var result = Alldatas
.AsEnumerable()
.GroupBy(r => r.TimeStamp.Day)
.Select(x => new {
Day = x.Key,
// Using Aggregate method
Value = x
.Select(y => y.Value)
.Aggregate(new List<double>(), (acc, list) =>
{
for (int i = 0; i < list.Count; ++i)
{
if (acc.Count == i) acc.Add(0);
acc[i] += list[i];
}
return acc;
}),
// Pure LINQ, using GroupBy
Value2 = x
// Create tuple (index, value) for each double
.SelectMany(y => y.Value.Select((z, i) => Tuple.Create(i, z)))
// Group by index
.GroupBy(y => y.Item1)
// Sum values within groups
.Select(y => y.Select(z => z.Item2).Sum())
// Make list
.ToList()
})
.OrderBy(x => x.Day)
.ToList();
For input:
var Alldatas = new []
{
new { TimeStamp = DateTime.Now, Value = new List<double> { 1, 2, 3 } },
new { TimeStamp = DateTime.Now, Value = new List<double> { 1, 2, 3 } },
new { TimeStamp = DateTime.Now, Value = new List<double> { 1, 2, 3 } }
};
This will produce following result:
new[] {
new { Day = 20, Value = new[] {3,6,9}, Value2 = new[] {3,6,9} }
}

Related

How can i use distinct with count in Linq?

The extention method below does not have Distinct and Count
public static IEnumerable<Something> ToFilterModel(this IEnumerable<Product> products)
{
var v = products
.SelectMany(x => x.ProductVariants)
.GroupBy(x => x.OptionId)
.Select(x => new
{
Id = x.Key.ToString(),
Items = x.Select(x => new Item { Id = x.ValueId, Text = x.Value.OptionValue })
});
return v;
}
Given the input below it should return 2 Items rows and not 3, since i am interested for ValueIds
and also Count by ValueIds
how should i modify it?
More spesifically it should return items with rows 1 and 2 and also
Count equal to 1 for the first row and Count equal to 2 for the second row.
You could group by ValueId the grouped options, like :
Items = x
.GroupBy(y => y.ValueId)
.Select(z => new Item { Id = z.Key, Text = z.First().Value.OptionValue, Count = z.Count() })
The result will be :
{
"Id":1,
"Items":[
{
"Id":1,
"Text":"text1",
"Count":1
},
{
"Id":2,
"Text":"text2",
"Count":2
}
]
}
NOTE : the Text is the count of grouped value ids.
The whole code :
var v = products
.SelectMany(x => x.ProductVariants)
.GroupBy(x => x.OptionId)
.Select(x => new
{
Id = x.Key.ToString(),
Items = x
.GroupBy(y => y.ValueId)
.Select(z => new Item { Id = z.Key, Text = z.First().Value.OptionValue, Count = z.Count() })
});

Select last wrong item from the list

I have a list with items, that have a Time property. If I want to select all items where Time is equal or bigger then some startTime, then I write something like this:
var newList = list.Where(i => (i.Time >= startTime));
But now I also want to get the last item, where the time is smaller than startTime. Is there a better way to implement this?
For example I have list where items have Time from this list:
[5:32, 5:46, 5:51, 6:07, 6:11, 6:36]
We specify a startTime as 6:00.
Now we want to get this times:
[5:51, 6:07, 6:11, 6:36]
Getting the whole List at once:
var newList = list
.OrderByDescending(i => i.Time)
.Take(list.Count(j => j.Time >= startTime) + 1)
.OrderBy(k => k.Time); //Optional
With Cognition's suggestion:
var newList = list
.OrderBy(i => i.Time)
.Skip(list.Count(j => j.Time < startTime - 1));
var result=list
.Where(i=>i.Time<startTime)
.OrderBy(i=>i.Time)
.Last()
.Concat(list
.OrderBy(i=>i.Time)
.Where(i=>i.Time>=startTime)
);
or
var result=list
.OrderBy(i=>i.Time)
.Last(i=>i.Time<startTime)
.Concat(list
.OrderBy(i=>i.Time)
.Where(i=>i.Time>=startTime)
);
var smallerThan = list
.Where(i => i.Time < startTime)
.OrderByDescending(o => o.Time)
.Take(1)
.Concat(list.Where(i => i.Time => startTime));
As your list is in order of the property you want to find, you can do something along the lines of
List<int> things = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
int threshold = 4;
var newThings = things.Skip(things.FindIndex(x => x >= threshold) - 1);
Console.WriteLine(string.Join(", ", newThings));
Which outputs
3, 4, 5, 6, 7, 8
Extending it to use a class with a Time property which happens to be a TimeSpan:
class Z
{
public TimeSpan Time { get; set; }
};
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
List<Z> zs = new List<Z>();
for (int i = 0; i < 10; i++)
{
zs.Add(new Z { Time = new TimeSpan(i, rand.Next(0,61), rand.Next(0,61)) });
}
TimeSpan threshold = new TimeSpan(4,0,0);
var newThings = zs.Skip(zs.FindIndex(x => x.Time >= threshold) - 1);
Console.WriteLine(string.Join(", ", newThings.Select(x => x.Time.ToString("c"))));
Console.ReadLine();
}
}
Sample output:
03:03:57, 04:09:37, 05:14:44, 06:58:55, 07:40:33, 08:37:06, 09:10:06
Many of the answers seem to require a descending orderby. But you can easily avoid this with a clean one liner and good efficiency:
var newList = list.Skip(list.Count(j => j.Time < startTime) - 1);
var newList = list
.Where(i => (i.Time >= startTime))
.ToList()
.Add(list
.Where(i => (i.Time < startTime))
.OrderByDescending(o => o.Time)
.FirstOrDefault()
)
int lastItemIndex = list.OrderBy(D => D.TimeOfDay).ToList()
.FindLastIndex(D => D.TimeOfDay < startTime);
var newList = list.Where(D => list.IndexOf(D) > lastItemIndex);

How do I return a list of the three lowest values in another list

How do I return a list of the 3 lowest values in another list. For example, I want to get the 3 lowest values like this:
in_list = [2, 3, 4, 5, 6, 1]
To this:
out_list: [2, 3, n, n, n, 1]
Maybe a function like this:
out_list = function(in_list, 3)?
in_list and ouput list is declared like this:
List<string> in_list = new List<string>();
List<string> out_list = new List<string>();
Can you help me developing a C# code for this? Further explanation can be given.
If you really want those weird n, there's this simple solution:
public static List<string> Function(List<string> inputList, int max)
{
var inputIntegers = inputList
.Select(z => int.Parse(z))
.ToList();
var maxAuthorizedValue = inputIntegers
.OrderBy(z => z)
.Take(max)
.Last();
return inputIntegers
.Select(z => z <= maxAuthorizedValue ? z.ToString() : "n")
.ToList();
}
public static void Main(string[] args)
{
List<string> in_list = new List<string> { "2", "3", "4", "6", "1", "7" };
var res = Function(in_list, 3);
Console.Read();
}
For your new requirement about duplicates, you could limit the max number of integer your return:
public static List<string> Function(List<string> inputList, int max)
{
var inputIntegers = inputList.Select(z => int.Parse(z)).ToList();
var maxAuthorizedValue = inputIntegers
.OrderBy(z => z)
.Take(max)
.Last();
// I don't really like that kind of LINQ query (which modifies some variable
// inside the Select projection), so a good old for loop would probably
// be more appropriated
int returnedItems = 0;
return inputIntegers.Select(z =>
{
return (z <= maxAuthorizedValue && ++returnedItems <= max) ? z.ToString() : "n";
}).ToList();
}
You need two queries, one to determine the lowest items and one to fill the result-list. You can use a HashSet for faster loookups:
var lowest = new HashSet<String>(in_list
.Select(s => new { s, val = int.Parse(s) })
.OrderBy(x => x.val)
.Take(3)
.Select(x => x.s));
List<string> out_list = in_list.Select(s => lowest.Contains(s) ? s : "n").ToList();
If you actually only want 3 and duplicates are possible this is the best i've come up with:
var lowest = new HashSet<String>(in_list
.Select(s => new { s, val = int.Parse(s) })
.Distinct()
.OrderBy(x => x.val)
.Take(3)
.Select(x => x.s));
List<string> out_list = in_list
.Select((str, index) => new { str, index, value = int.Parse(str) })
.GroupBy(x => x.str)
.SelectMany(g => lowest.Contains(g.Key)
? g.Take(1).Concat(g.Skip(1).Select(x => new { str = "n", x.index, x.value }))
: g.Select(x => new { str = "n", x.index, x.value }))
.OrderBy(x => x.index)
.Select(x => x.str)
.ToList();
You could use Aggregate to grab a Dictionary of each element with its corresponding number of allowed occurrences which you could then use to grab your values from the input list:
public static List<string> GetList(List<string> in_list, int max)
{
Dictionary<string, int> occurrences = new Dictionary<string, int>();
int itemsAdded = 0;
in_list.OrderBy(x => x).Aggregate(occurrences, (list, aggr) =>
{
if (itemsAdded++ < max)
{
if (occurrences.ContainsKey(aggr))
occurrences[aggr]++;
else
occurrences.Add(aggr, 1);
}
return list;
});
//occurrences now contains only each required elements
//with the number of occurrences allowed of that element
List<string> out_list = in_list.Select(x =>
{
return (occurrences.ContainsKey(x) && occurrences[x]-- > 0 ? x : "n");
}).ToList();
return out_list;
}

Append index number to duplicated string value in a list - by using Lambda

I have a IList<string>() which holds some string values, and there could be duplicated items in the list. What I want is to append a index number to end of the string to eliminate the duplication.
For example, I have these values in my list: StringA, StringB, StringC, StringA, StringA, StringB. And I want the result looks like: StringA1, StringB1, StringC, StringA2, StringA3, StringB2. I need to retain the original order in list.
Is there a way I can just use one Lambda expression?
You are looking for something like this:
yourList.GroupBy(x => x)
.SelectMany(g => g.Select((x,idx) => g.Count() == 1 ? x : x + idx))
.ToList();
Edit: If the element order matters, here is another solution:
var counts = yourList.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
var values = counts.ToDictionary(x => x.Key, x => 0);
var list = yourList.Select(x => counts[x] > 1 ? x + ++values[x] : x).ToList();
You can do:
List<string> list = new List<string> { "StringA", "StringB", "StringC", "StringA", "StringA", "StringB" };
var newList =
list.Select((r, i) => new { Value = r, Index = i })
.GroupBy(r => r.Value)
.Select(grp => grp.Count() > 1 ?
grp.Select((subItem, i) => new
{
Value = subItem.Value + (i + 1),
OriginalIndex = subItem.Index
})
: grp.Select(subItem => new
{
Value = subItem.Value,
OriginalIndex = subItem.Index
}))
.SelectMany(r => r)
.OrderBy(r => r.OriginalIndex)
.Select(r => r.Value)
.ToList();
and you will get:
StringA1,StringB1,StringC,StringA2,StringA3,StringB2
If you don't want to preserve order then you can do:
var newList = list.GroupBy(r => r)
.Select(grp => grp.Count() > 1 ?
grp.Select((subItem, i) => subItem + (i + 1))
: grp.Select(subItem => subItem))
.SelectMany(r => r)
.ToList();
This uses some lambda expressions and linq to do it, maintaining the order but I'd suggested a function with a foreach loop and yield return would be better.
var result = list.Aggregate(
new List<KeyValuePair<string, int>>(),
(cache, s) =>
{
var last = cache.Reverse().FirstOrDefault(p => p.Key == s);
if (last == null)
{
cache.Add(new KeyValuePair<string, int>(s, 0));
}
else
{
if (last.Value = 0)
{
last.Value = 1;
}
cache.Add(new KeyValuePair<string, int>(s, last.Value + 1));
}
return cache;
},
cache => cache.Select(p => p.Value == 0 ?
p.Key :
p.Key + p.Value.ToString()));

C# LINQ: Get items with max price

I have a list of my objects:
class MyObj
{
public String Title { get; set; }
public Decimal Price { get; set; }
public String OtherData { get; set; }
}
var list = new List<MyObj> {
new MyObj { Title = "AAA", Price = 20, OtherData = "Z1" },
new MyObj { Title = "BBB", Price = 20, OtherData = "Z2" },
new MyObj { Title = "AAA", Price = 30, OtherData = "Z5" },
new MyObj { Title = "BBB", Price = 10, OtherData = "Z10" },
new MyObj { Title = "CCC", Price = 99, OtherData = "ZZ" }
};
What is the best way to get list with unique Title and MAX(Price).
Resulting list needs to be:
var ret = new List<MyObj> {
new MyObj { Title = "BBB", Price = 20, OtherData = "Z2" },
new MyObj { Title = "AAA", Price = 30, OtherData = "Z5" },
new MyObj { Title = "CCC", Price = 99, OtherData = "ZZ" }
};
Well, you could do:
var query = list.GroupBy(x => x.Title)
.Select(group =>
{
decimal maxPrice = group.Max(x => x.Price);
return group.Where(x => x.Price == maxPrice)
.First();
};
If you need LINQ to SQL (where you can't use statement lambdas) you could use:
var query = list.GroupBy(x => x.Title)
.Select(group => group.Where(x => x.Price == group.Max(y => y.Price))
.First());
Note that in LINQ to Objects that would be less efficient as in each iteration of Where, it would recompute the maximum price.
Adjust the .First() part if you want to be able return more than one item with a given name if they both have the same price.
Within LINQ to Objects you could also use MoreLINQ's MaxBy method:
var query = list.GroupBy(x => x.Title)
.Select(group => group.MaxBy(x => x.Price));
var ret = list.GroupBy(x => x.Title)
.Select(g => g.Aggregate((a, x) => (x.Price > a.Price) ? x : a));
(And if you need the results to be a List<T> rather than an IEnumerable<T> sequence then just tag a ToList call onto the end.)
var ret = list.OrderByDescending(x => x.Price).GroupBy(x => x.Title).Select(#group => #group.ElementAt(0)).ToList();
this should do it.
Would like to mention that
var query = list.GroupBy(x => x.Title)
.Select(group => group.Where(x => x.Price == group.Max(y => y.Price))
.First());
Should be
var query = list.GroupBy(x => x.Title)
.First(group => group.Where(x => x.Price == group.Max(y => y.Price)));
I like the Richard solution to greatest-n-per-group problem.
var query = list
.OrderByDescending(o => o.Price) //set ordering
.GroupBy(o => o.Title) //set group by
.Select(o => o.First()); //take the max element
However it needs to be slightly modified
var query = list
.OrderByDescending(o => o.Price) //set ordering
.GroupBy(o => o.Title) //set group by
.Select(o => o.Where(k => k.Price == o.First().Price)) //take max elements

Categories