0

How to convert below c# nested for loop to linq...?

 list = objBLForms.GetForms(Ids);
            for (int i = 0; i < list.Count; i++)
            {
                for (int j = 0; j < list.Count; j++)
                {
                    if (list[i].StateId == list[j].StateId && 
                    list[i].PayerId == list[j].PayerId && i != j)
                    {
                        if (string.IsNullOrEmpty(list[i].Tax))
                        {
                            list.Remove(list[i]);
                        }
                        else
                        {
                            list.Remove(list[j]);
                        }
                    }
                }
            }

I want to Remove duplicate payers with same state..And if any state tax is present, i wanted to remove the other duplicate one i,e; the duplicate one which is having no state tax... I have achived it by using the nested for loop as shown above. is there any way to do it in linq..I dont't know anything about linq. Am very new to linq,Thanks in advance

4
  • Note that && i != j isn't needed: just start j at 1 rather than 0. Commented Nov 13, 2018 at 5:33
  • yes,@john..that's a good idea! Commented Nov 13, 2018 at 5:37
  • Both for loops start at 0 and both end at Count. You are bound to compare an object to its own self Commented Nov 13, 2018 at 5:39
  • yes @ahmmed.. i wanted to remove duplicates, so i need to compare to its own self only... Commented Nov 13, 2018 at 5:41

2 Answers 2

1

The logic of your code is actually removing EVERYTHING that has string.IsNullOrEmpty(Tax), and only keeping first record that has value in Tax. Then, how about this

list
    .Where(l => !string.IsNullOrEmpty(l.Tax))
    .GroupBy(l => new {l.StateId, l.PayerId})
    .Select(group => group.First())
    .ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

it removing every item where tax is empty...but only remove empty tax item when there exist an other duplicate item with tax, else keep that empty tax item in the list
0

This seems about right to me:

list =
    list
        .OrderByDescending(x => x.Tax)
        .GroupBy(x => new { x.StateId, x.PayerId })
        .SelectMany(x => x.Take(1))
        .ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.