how to use conditional sum linq c# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What is wrong here? How to filter out negative elements correctly?
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 2, -3, 4, 5, -1, 4, -2 };
double sumOfElem = array.Sum(element => element < 0);
Console.WriteLine(sumOfElem);
}
}

I think you need this:
double sumOfElem = array.Sum(element => (element < 0 ? 0 : element));
This way you are using an overload of Sum that utilises a transform function (so called selector), that is applied to each element of the array.
The above filters out negative elements. If you want to filter out positive ones, then simply inverse the comparison operator:
double sumOfElem = array.Sum(element => (element > 0 ? 0 : element));

You could try this one:
int sumOfElem = array.Where(element => element < 0)
.Sum();
You can't filter your values inside the Sum. You should first filter the values and then sum them.
Update
Saying that You can't filter your values inside the Sum, I mean you can't pass a predicate in the Sum method.

Related

make dictionary that will loop every 9 numbers. C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
Im new to programming and sorry if I cant explain properly. I am trying to iterate through a list that has items in it in multiples of 9. So the list can have 9,18,27.. items.
I have the code working for it to read when there is 9 using this dictionary. But I would like it work for any amount in multiples of 9.
var alphabets = new Dictionary<int, string>()
{
{1,"A2"},{2,"B2"},{3,"C2"},{4"D2"},
{5,"E2"},{6,"F2"}, {7,"G2"},{8,"H2"},
{9,"I2"}
};
So for example if there was 18 items it would like this dictionary to have this function.
var alphabets2 = new Dictionary<int, string>()
{
{1,"A2"},{2,"B2"},{3,"C2"},{4"D2"},
{5,"E2"},{6,"F2"}, {7,"G2"},{8,"H2"},
{9,"I2"},
{10,"A3"},{11,"B3"},{12,"C3"},{13"D3"},
{14,"E3"},{15,"F3"}, {16,"G3"},{17,"H3"},
{18,"I3"}
};
Thank you
As #DiplomacyNotWar commented, it sounds as if you need to input int value to convert to a correlating string value which is uniformly based on multiples of 9. If this is the case, I agree with #DiplomacyNotWar that you don't need to store anything but create a function to output the needed string value based on an int value. Here is a function that will output the pattern in your examples.
// value should be 0
string ConvertIntToSpecificString(int value)
{
// this will give you an int value 0-8
var modValue = (value - 1) % 9;
// The unicode for 'A' is 65
var firstCharValue = (char)(65 + modValue);
// This will return a whole number giving the iteration count. FE: 19 / 9 = 2
// Adding 2 to fit the pattern stated in the examples.
var secondValue = ( value / 9 ) + 2 ;
return $"{firstCharValue}{secondValue}";
}

Find max value in each of the index of a collection of integers in c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have a List<List<int>>.
All the list will be of equal size. I need to find the max value in every index of the list.
ie if I have 100 list each of size 3. I need to find the max value at index 0,1 and 2 across the 100 items.
ie
Max value out of list1[0], list2[0], list3[0],......list100[0]
Max value out of list1[1], list2[1], list3[1],......list100[1]
Max value out of list1[2], list2[2], list3[2],......list100[2]
Need a function which accepts the List<List<int>> and returns an list with max value of each index. Like below
public List<int> FindMaxValueByIndex(List<List<int>> items)
{
}
Performance is a key factor that needs to be considered.
Ignoring data validation & guaranteeing the inner lists will always have the same number of elements:
public List<int> FindMaxValueByIndex(List<List<int>> items)
{
var maxListSize = items[0].Count;
var maxValues = new List<int>(items.Count);
for (var index = 0; index < maxListSize; index++)
maxValues.Add(items.Select(x => x[index]).Max());
return maxValues;
}
Input:
var data = new List<List<int>>
{
new List<int> { 5, 10, 300, 1 },
new List<int> { 3, 24, 2, 56 },
};
Output:
{5, 24, 300, 56}
I would recommend such approach using LINQ methods :)
private static int[] FindMaxByIndex(List<List<int>> lists)
{
var listLength = lists
.Select(x => x.Count)
.Distinct()
// If all lists are of equal length
// this should contain single element.
// Otherwise this would throw exception -
// this is validation.
.Single();
var maxesByIndex = new int[listLength];
for (int i = 0; i < listLength; i++)
{
maxesByIndex[i] = lists
.Select(x => x[i])
.Max();
}
return maxesByIndex;
}
I understand that the question states that the lists will always be the same size, however, since a generic list of generic lists is used and a generic list of generic lists does not enforce that requirement, this code takes the safe approach of ensuring that out of bounds indices are not accessed.
public List<int> FindMaxValueByIndex(List<List<int>> items)
{
List<int> ret = new List<int>();
var MaxListSize = items.Select(l => l.Count).Max();
for(int i = 0; i < MaxListSize; i ++)
{
ret.Add(items.Where(l => l.Count > i).Select(l => l[i]).Max());
}
return ret;
}
Fiddle

How to solve Sales by Match problem using c#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have challenge to solve Sales by Match problem using c# without use List collection ?
*Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are N =7 socks with colors ar=[1,2,1,2,1,3,2] There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2 .*
you can try this code
static int sockMerchant(int n, int[] ar) {
int matchingPairsCount= 0 ;
int[] arr =new int[n];
var ix=0;
for (int i = 0 ; i< ar.Length ; i++)
{
int countPairs = 0 ;
for(int j = 0 ;j< ar.Length ;j++)
{
if(ar[i] == ar[j] && i<j&& (!arr.Contains(i)|| i==0))
{
arr[ix]=j;
ix++;
matchingPairs = matchingPairs + 1 ;
break;
}
}
}
return matchingPairsCount;
}
You can use it using the following code
var ar = new int[] { 1,2,1,2,1,3,2 };
ar.GroupBy( g => g ).Sum( g => Math.Floor( g.Count() / 2.0 ) );
It groups all the items in the array first, and then sums up all pairs. You can try it here

Alphabetize list by using last 3 characters with C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a list of strings like this:
123.45 ABC
678.90 DEF
543.21 FED
I want to sort the list alphabetically using the last 3 characters of each list element.
EDIT: Using C#, how do I alphabetize this list by using the last 3 characters of each element?
What I would first do is to ensure that I filter out all strings that have less than 3 characters. Then I would order them as:
var items = new List<string> { "13 zzz", "12 yyy", "11 zzz" };
items = items.Where(i => i.Length > 2)
.OrderBy(i => i.Substring(i.Length - 3))
.ToList();
To order by the last three characters, you can just take the Substring starting at Length - 3 and use that in the OrderBy method (note that we should first check that item.Length > 2 so that Substring doesn't throw an execption):
var items = new List<string> {"543.21 FED", "123.45 ABC", "678.90 DEF"};
items = items
.OrderBy(item => item?.Length > 3 ? item.Substring(item.Length - 3) : item)
.ToList();
// result: {"123.45 ABC", "678.90 DEF", "543.21 FED"}
Alternatively, you can write a custom comparer for the strings and then pass that to the Sort method. We can include a constructor for our comparer that takes in an int that specifies how many characters we want to count from the end of the string to make it more flexible (like if you want to use the last 5 characters, or the last 2, etc.).
public class OrderByLastNChars : Comparer<string>
{
public int N { get; set; }
public OrderByLastNChars(int n)
{
N = n;
}
public override int Compare(string x, string y)
{
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
var first = x.Length > N ? x.Substring(x.Length - N) : x;
var second = y.Length > N ? y.Substring(x.Length - N) : y;
return first.CompareTo(second);
}
}
Then this can be used like:
items.Sort(new OrderByLastNChars(3));

LinQ How to get all the data from the range of numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am new to LinQ and I want to get all the data from a range of numbers when I pass a parameter. For an example, the range is 1-100 and I pass in 40, it should get all the data from 1-100 but not only 40. Any ideas?
Thanks
You can use Enumerable.Range which will give you range of numbers. You can use Except method to remove the numbers that you dont want.
private static int[] GetRange(int start,int inclusiveEnd,int[] except)
{
return Enumerable.Range(start, inclusiveEnd - start + 1).Except(except).ToArray();
}
Then call it in this way.
var x = GetRange(1, 100, new[] {40});
Use filtering (i.e. Where statement):
var result = Enumerable.Range(1,100).Where(x=>x != 40).ToList()
List<int> list = new List<int>();
var result = list.Where(i=> i >= 1 && i <= 100 && i != 40);
Assuming, that there is a function, that transforms a number from given range into some data:
Enumerable.Range(1, 100).Where(_ => _ != 40).Select(_ => GetData(_));
Use Except extension method From MSDN
List<int> oldList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int parameter = 2;
List<int> newList = oldList.Except(new int[] { parameter }).ToList<int>();

Categories

Resources