I'm trying to get all the assets where Class property equals to one of the values in selectedIClassesList;
Something like this:
from x in Assets where selectedIClassesList.Contains(x.Class) select x
I am trying to construct a navigation menu using a Categories table from my db.
I have a similar layout as below in Categories table.
public List<Category> CategoryData = new List(new Category[] {
new Category{ CategoryId = 1, Name = "Fruit", ParentCategoryId = null},
new Category{ CategoryId = 2, Name = "Vegetables", ParentCategoryId = null},
new Category{ CategoryId = 3, Name = "Apples", ParentCategoryId = 1},
new Category{ CategoryId = 4, Name = "Bananas", ParentCategoryId = 1},
new Category{ CategoryId = 5, Name = "Cucumber", ParentCategoryId = 2},
new Category{ CategoryId = 6, Name = "Onions", ParentCategoryId = 2}
); }
The above should return something like
Fruit (parent)
"===Apples, Bananas (child)
Vegetables (parent)
"===Cucumber, Onions (child)
I need to be able to pass this as some kind of 'grouped' (grouped by parentid) collection to my View.
How to do this?
I can understand what the error is saying - it can't compare a list. Not a problem, other than the fact that I don't know how to not have it compare a list when I want to page through a model with a list as a property.
My Model:
Event : IEvent
int Id
string Title
// Other stuff..
LazyList<EventDate> Dates // The "problem" property
Method which pages the data (truncated):
public JsonResult JsonEventList(int skip, int take) {
var query = _eventService.GetEvents();
// Do some filtering, then page data..
query = query.Skip(skip).Take(take);
return Json(query.ToArray());
}
As I said, the above is truncated quite a bit, leaving only the main point of the function: filter, page and return JSON'd data.
The exception occurs when I enumerate (.ToArray()). The Event object is really only used to list the common objects of all the event types (Meetings, Birthdays, etc - for example). It still implements IEvent like the other types, so I can't just remove the LazyList<EventDate> Dates' property unless I no longer implementIEvent`
Anyway, is there a way to avoid this? I don't really want to compare a LazyList when I page, but I do not know how to resolve this issue.
Thank you in advance! :)
I am trying to process some list with a functional approach in C#.
The idea is that I have a collection of Tuple<T,double> and I want to change the Item 2 of some element T.
The functional way to do so, as data is immutable, is to take the list, filter for all elements where the element is different from the one to change, and the append a new tuple with the new values.
My problem is that I do not know how to append the element at the end. I would like to do:
public List<Tuple<T,double>> Replace(List<Tuple<T,double>> collection, T term,double value)
{
return collection.Where(x=>!x.Item1.Equals(term)).Append(Tuple.Create(term,value));
}
But there is no Append method. Is there something else?
I have this simple code but it shows error. I dont know where I am going wrong.
I shows error in last line.."DeleteOnSubmit"
linq_testDataContext db = new linq_testDataContext();
var remove = from aremove in db.logins
where aremove.username == userNameString && aremove.Password == pwdString
select aremove;
db.logins.DeleteOnSubmit(remove);
Thanks,
Ani
I have questions that may or may not have a question_group
if all the questions do not have a question_group and if I use default if empty like this:
question_group defaultQuestion = new question_group {question_group_id = Guid.Empty};
questions.Select(x => x.question_group).DefaultIfEmpty(defaultQuestion).Distinct();
shouldn't I get an IEnumerable<question_group> containing only the default question_group that I defined? I get null.... what am I missing here?
Hello All
i have a US states list
List<string> state // contain all 51 US states
Now i have a string which contain some text like okl (it means Oklahoma for me). what i want i want 'like' query in List state and get Oklahoma state.
Hi!
I have a table (sql server). One of its columns ('Name') Contains Cyrillic values.
From parameters i recieve value, that contains in this field but the are transliterated.
i mean something like:
var q = from r in m_DataContext.Table where CTransliteration.Transliterate(r.Name).Contains(trans_text) select r;
How can i transliterate value on-fly?
I have a learning project where a data grid is filtered by 3 controls (a checkbox and 2 dropdowns)
I'm about to wrap up and move on to another project as it works well but I don't like the complexity of nesting IF statements to capture all the possible combinations of the 3 filters and was wondering if there is a better way. For example: Something that would allow for more filters to be added easily rather than walking through all the nests and adding another level of madness.
private void BuildQuery()
{
EntityQuery<MASTER_DOCKS> query = QDocksContext.GetMASTER_DOCKSQuery();
if (Tonnage.IsChecked.HasValue && Tonnage.IsChecked.Value)
{
if (null != FilterWaterWay.SelectedValue)
{
string WaterwaytoFilterBy = FilterWaterWay.SelectedValue.ToString();
if (!string.IsNullOrWhiteSpace(WaterwaytoFilterBy) && WaterwaytoFilterBy != "[Select WaterWay]")
{
if (null != FilterState.SelectedValue)
{
string StateToFilterBy = FilterState.SelectedValue.ToString();
if (null != FilterState.SelectedValue && !string.IsNullOrWhiteSpace(StateToFilterBy) && StateToFilterBy != "[Select State]")
{
if (!string.IsNullOrWhiteSpace(StateToFilterBy) && StateToFilterBy != "[Select State]")
{
query = query.Where(s => s.WTWY_NAME == WaterwaytoFilterBy && s.STATE == StateToFilterBy && (s.Tons != "0" && s.Tons != "")).OrderBy(s => s.WTWY_NAME);
MyQuery.Text = "Tonnage, WW and State";
}
}
if (StateToFilterBy == "[Select State]") //waterway but no state
{
query = query.Where(s => s.WTWY_NAME == WaterwaytoFilterBy && (s.Tons != "0" && s.Tons != "")).OrderBy(s => s.WTWY_NAME);
MyQuery.Text = "Tonnage, WW No State";
}
}
}
else
{
if (null != FilterState.SelectedValue)
{
string StateToFilterBy = FilterState.SelectedValue.ToString();
if (null != FilterState.SelectedValue && !string.IsNullOrWhiteSpace(StateToFilterBy) && StateToFilterBy != "[Select State]")
{
if (!string.IsNullOrWhiteSpace(StateToFilterBy) && StateToFilterBy != "[Select State]")
{
query = query.Where(s => s.STATE == StateToFilterBy && (s.Tons != "0" && s.Tons != "")).OrderBy(s => s.WTWY_NAME);
MyQuery.Text = "Tonnage State No WW";
}
}
else
{
query = query.Where(s => (s.Tons != "0" && s.Tons != ""));
MyQuery.Text = "Tonnage No State No WW";
}
}
}
}
}
else //no tonnage
{
if (null != FilterWaterWay.SelectedValue)
{
string WaterwaytoFilterBy = FilterWaterWay.SelectedValue.ToString();
if (!string.IsNullOrWhiteSpace(WaterwaytoFilterBy) && WaterwaytoFilterBy != "[Select WaterWay]")
{
if (null != FilterState.SelectedValue)
{
string StateToFilterBy = FilterState.SelectedValue.ToString();
if (null != FilterState.SelectedValue && !string.IsNullOrWhiteSpace(StateToFilterBy) && StateToFilterBy != "[Select State]")
{
if (!string.IsNullOrWhiteSpace(StateToFilterBy) && StateToFilterBy != "[Select State]")
{
query = query.Where(s => s.WTWY_NAME == WaterwaytoFilterBy && s.STATE == StateToFilterBy).OrderBy(s => s.WTWY_NAME);
MyQuery.Text = "No Tonnage, WW and State";
}
}
if (StateToFilterBy == "[Select State]") //waterway but no state
{
query = query.Where(s => s.WTWY_NAME == WaterwaytoFilterBy).OrderBy(s => s.WTWY_NAME);
MyQuery.Text = "No Tonnage, WW No State";
}
}
}
else
{
if (null != FilterState.SelectedValue)
{
string StateToFilterBy = FilterState.SelectedValue.ToString();
if (null != FilterState.SelectedValue && !string.IsNullOrWhiteSpace(StateToFilterBy) && StateToFilterBy != "[Select State]")
{
if (!string.IsNullOrWhiteSpace(StateToFilterBy) && StateToFilterBy != "[Select State]")
{
query = query.Where(s => s.STATE == StateToFilterBy).OrderBy(s => s.WTWY_NAME);
MyQuery.Text = "No Tonnage State No WW";
}
}
else
{
LoadAllData();
MyQuery.Text = "No Tonnage No State No WW";
}
}
}
}
}
LoadOperation<MASTER_DOCKS> loadOp = this.QDocksContext.Load(query);
DocksGrid.ItemsSource = loadOp.Entities;
}
Here is an interesting issue I noticed when using the Except Operator:
I have list of users from which I want to exclude some users:
The list of users is coming from an XML file:
The code goes like this:
interface IUser
{
int ID { get; set; }
string Name { get; set; }
}
class User: IUser
{
#region IUser Members
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
#endregion
public override string ToString()
{
return ID + ":" +Name;
}
public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users)
{
IEnumerable<IUser> localList = new List<User>
{
new User{ ID=4, Name="James"},
new User{ ID=5, Name="Tom"}
}.OfType<IUser>();
var matches = from u in users
join lu in localList
on u.ID equals lu.ID
select u;
return matches;
}
}
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("Users.xml");
IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select
(u => new User
{ ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType<IUser>(); //still a query, objects have not been materialized
var matches = User.GetMatchingUsers(users);
var excludes = users.Except(matches); // excludes should contain 6 users but here it contains 8 users
}
}
When I call User.GetMatchingUsers(users) I get 2 matches as expected.
The issue is that when I call users.Except(matches) The matching users are not being excluded at all! I am expecting 6 users ut "excludes" contains all 8 users instead.
Since all I'm doing in GetMatchingUsers(IEnumerable users) is taking the IEnumerable and just returning
the IUsers whose ID's match( 2 IUsers in this case), my understanding is that by default "Except" will use reference equality
for comparing the objects to be excluded. Is this not how "Except" behaves?
What is even more interesting is that if I materialize the objects using .ToList() and then get the matching users, and call "Except",
everything works as expected!
Like so:
IEnumerable users = doc.Element("Users").Elements("User").Select
(u = new User
{ ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType().ToList(); //explicity materializing all objects by calling ToList()
var matches = User.GetMatchingUsers(users);
var excludes = users.Except(matches); // excludes now contains 6 users as expected
I don't see why I should need to materialize objects for calling "Except" given that its defined on IEnumerable?
Any suggesstions / insights would be much appreciated.
I have a Logins table which records when user is login, logout or loginFailed and its timestamp. Now I want to get the list of loginFailed after last login and the loginFailed happened within 24 hrs.
What I am doing now is get the last login timestamp first. then use second query to get the final list. do you think I should join those two queris together? why not? why yes?
var lastLoginTime = (from inRecord in db.Logins
where inRecord.Users.UserId == userId
&& inRecord.Action == "I"
orderby inRecord.Timestamp descending
select inRecord.Timestamp).Take(1);
if (lastLoginTime.Count() == 1)
{
DateTime lastInTime = (DateTime)lastLoginTime.First();
DateTime since = DateTime.Now.AddHours(-24);
String actionStr = "F";
var records = from record in db.Logins
where record.Users.UserId == userId
&& record.Timestamp >= since
&& record.Action == actionStr
&& record.Timestamp > lastInTime
orderby record.Timestamp
select record;
}
Hi,
I have a class
Class MyObject
{
decimal v1;
decimal dv1;
decimal v2;
decimal dv2;
}
and a
List<MyObject> ...
I need to process every element of the list by adding dv1 to v1 and dv2 to v2
Something like (pseudo-syntax):
myList.Transform(o=>o.v1+=o.dv1, o.v2+=o.dv2)
How can I do this (obvious my pseudo-syntax doesn't works)?
Thank you
Here I had very similar xml structure, but now I have this:
<Fields>
<Company>My Company</Company>
<Address2>Villa at beach</Address2>
<Email2>[email protected]</Email2>
<Mobile>333-888</Mobile>
<ContactMethod>Facebook</ContactMethod>
</Fields>
And now I need the same output as on the given link:
Company: My Company
Address2: Villa at beach
Email2: [email protected]
What would be the query for it?
Thanks,
Ile
My intention here is to select all entries (Bookings) between "begin" (begin_prefix) and "end" (end_prefix)
BUT! The important thing is:
If I have a booking at 07:25-10:00 - you query for 09:00-10:00 it should still show the booking because it reserves the room until 10 no matter what ..
So ..
07.25-10.00 booking means query for 09:00-10.00 still returns a list of bookings within 09:00-10.00 (which means 07.25-10.00 is included)
public static List<booking> Today(DateTime begin, DateTime end)
{
try
{
IFormatProvider Culturez = new CultureInfo(ConfigurationManager.AppSettings["locale"].ToString(), true);
DateTime begin_prefix = DateTime.ParseExact(begin.ToString(), "dd-MM-yyyy HH:mm:ss", Culturez);
DateTime end_prefix = DateTime.ParseExact(end.ToString(), "dd-MM-yyyy HH:mm:ss", Culturez);
dbDataContext db = new dbDataContext();
// gives bookings BEFORE begin_prefix (why?)
IQueryable<booking> bQ = from b in db.bookings
where begin_prefix >= b.Starts &&
b.Ends <= end_prefix &&
b.Ends > b.Starts &&
b.pointsbookings.Count > 0
select b;
// ^gives bookings BEFORE begin_prefix (why?)
List<booking> bL = bQ.ToList();
return bL;
}
catch (Exception)
{
throw;
}
}
I've tried getting this right for some time now .. Seems everytime I correct it to something new, a new overlap or selection outside the two begin/end dates seem to appear :(
UPDATE CRITERIA and SOURCE: Bookings has to be WITHIN "begin_prefix" and "end_prefix" or on the exact same time ..
.. currently the above code gives me bookings BEFORE begin_prefix date, which is not intentioned! We're in 2011, I got bookings from 2010 as well! **
NEW!! UPDATED:
This is what I have:
SEARCH.START = BOOKING.START
BOOKING.END <= SEARCH.END
... the problem comes up when ..
BOOKING entry: 10:00(Start)-14:00(End)
This means according to above:
08.59 = 10.00
(SEARCH.START = BOOKING.START)
It will never include it. But it should, since this is the same room and the seats are booked individually!
I use c# 4 asp.net and EF 4. I'm precompiling a query, the result should be a collection of Anonymous Type.
At the moment I use this code.
public static readonly Func<CmsConnectionStringEntityDataModel, string, dynamic>
queryContentsList =
CompiledQuery.Compile<CmsConnectionStringEntityDataModel, string, dynamic>
(
(ctx, TypeContent) => ctx.CmsContents.Where(c => c.TypeContent == TypeContent
& c.IsPublished == true & c.IsDeleted == false)
.Select(cnt => new
{
cnt.Title,
cnt.TitleUrl,
cnt.ContentId,
cnt.TypeContent, cnt.Summary
}
)
.OrderByDescending(c => c.ContentId));
I suspect the RETURN for the FUNCTION Dynamic does not work properly and I get this error
Sequence contains more than one element enter code here.
I suppose I need to return for my function a Collection of Anonymous Types...
Do you have any idea how to do it? What I'm doing wrong? Please post a sample of code thanks!
Update:
public class ConcTypeContents
{
public string Title { get; set; }
public string TitleUrl { get; set; }
public int ContentId { get; set; }
public string TypeContent { get; set; }
public string Summary { get; set; }
}
public static readonly Func<CmsConnectionStringEntityDataModel, string, ConcTypeContents> queryContentsList =
CompiledQuery.Compile<CmsConnectionStringEntityDataModel, string, ConcTypeContents>(
(ctx, TypeContent) => ctx.CmsContents.Where(c => c.TypeContent == TypeContent & c.IsPublished == true & c.IsDeleted == false)
.Select(cnt => new ConcTypeContents { cnt.Title, cnt.TitleUrl, cnt.ContentId, cnt.TypeContent, cnt.Summary }).OrderByDescending(c => c.ContentId));
I have a logins table which records all login and logout activities. I want to look at all login activities of a particular user within 24 hrs. how to do it? something like this:
var records = from record in db.Logins
where record.Users.UserId == userId
&& record.Timestamp <= (DateTime.Now + 24)
select record;
record.Timestamp <= (DateTime.Now + 24) is wrong here. I am using C# 3 + L2E.
OK so I've got 2 tables for this instance, Users{UserID, Name}, Company{CompanyID, UserID, Name, Payrate}
i also have 2 combo boxes, first one is for Users which Displays Name, and the Value is UserID
i need the second combobox to get the Names from the Company table, but only showing Companies that are relevant to the selected user. I cant work out how to get it to go...
Any ideas???
I have a website for dance academy where Users can register and add/drop dance classes.
In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances.
Now I want to delete one of the dances from the list. So I'll remove the row from the table and also from the dropdownlist. The problem is that everytime the item with the lowest ID (index) is getting deleted, no matter which one the user selects. I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. The code is:
private void PopulateDanceDropDown()
{
// Retrieve the username
MembershipUser currentUser = Membership.GetUser();
var username = currentUser.UserName;
// Retrive the userid of the curren user
var dancerIdFromDB = from d in context.DANCER
where d.UserName == username
select d.UserId;
Guid dancerId = new Guid();
var first = dancerIdFromDB.FirstOrDefault();
if (first != null)
{
dancerId = first;
}
dances.DataSource = (from dd in context.DANCER_AND_DANCE
where dd.UserId == dancerId
select new
{
Text = dd.DanceName,
Value = dd.DanceId
}).ToList();
dances.DataTextField = "Text";
dances.DataValueField = "Value";
dances.DataBind();
}
protected void dropthedance(object o, EventArgs e)
{
String strDataValueField = dances.SelectedItem.Value;
int danceIDFromDropDown = Convert.ToInt32(strDataValueField);
var dancer_dance = from dd in context.DANCER_AND_DANCE
where dd.DanceId == danceIDFromDropDown
select dd;
foreach (var dndd in dancer_dance)
{
context.DANCER_AND_DANCE.DeleteOnSubmit(dndd);
}
try
{
context.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
The problem is in the line:
String strDataValueField = dances.SelectedItem.Value;
The strDataValueField is always getting the minimum id from the list of dance item ids in the dropdown (which happens by default). I want this to hold the id of the dance selected by the user.
I have a business layer that has DTOs that are used in the presentation layer. This application uses entity framework.
Here is an example of a class called RoleDTO:
public class RoleDTO
{
public Guid RoleId { get; set; }
public string RoleName { get; set; }
public string RoleDescription { get; set; }
public int? OrganizationId { get; set; }
}
In the BLL I want to have a method that returns a list of DTO. I would like to know which is the better approach: returning IQueryable or list of DTOs. Although I feel that returning IQueryable is not a good idea because the connection needs to be open. Here are the 2 different methods using the different approaches:
First approach
public class RoleBLL
{
private servicedeskEntities sde;
public RoleBLL()
{
sde = new servicedeskEntities();
}
public IQueryable<RoleDTO> GetAllRoles()
{
IQueryable<RoleDTO> role = from r in sde.Roles
select new RoleDTO()
{
RoleId = r.RoleID,
RoleName = r.RoleName,
RoleDescription = r.RoleDescription,
OrganizationId = r.OrganizationId
};
return role;
}
Note: in the above method the DataContext is a private attribute and set in the constructor, so that the connection stays opened.
Second approach
public static List<RoleDTO> GetAllRoles()
{
List<RoleDTO> roleDTO = new List<RoleDTO>();
using (servicedeskEntities sde = new servicedeskEntities())
{
var roles = from pri in sde.Roles
select new { pri.RoleID, pri.RoleName, pri.RoleDescription };
//Add the role entites to the DTO list and return. This is necessary as anonymous types can be returned acrosss methods
foreach (var item in roles)
{
RoleDTO roleItem = new RoleDTO();
roleItem.RoleId = item.RoleID;
roleItem.RoleDescription = item.RoleDescription;
roleItem.RoleName = item.RoleName;
roleDTO.Add(roleItem);
}
return roleDTO;
}
}
Please let me know, if there is a better approach.
hi, i want to remove repeated record's from results but distinct don't do this for me! why???
var results = (from words in _Xplorium.Words
join wordFiles in _Xplorium.WordFiles on words.WordId equals wordFiles.WordId
join files in _Xplorium.Files on wordFiles.FileId equals files.FileId
join urls in _Xplorium.Urls on files.UrlId equals urls.UrlId
where files.Title.Contains(query) || files.Description.Contains(query)
orderby wordFiles.Count descending
select new SearchResultItem()
{
Title = files.Title,
Url = urls.Address,
Count = wordFiles.Count,
CrawledOn = files.CrawledOn,
Description = files.Description,
Lenght = files.Lenght,
UniqueKey = words.WordId + "-" + files.FileId + "-" + urls.UrlId
}).Distinct();
Following code
ProductPricesDataContext db = new ProductPricesDataContext();
var products = from p in db.Products
where p.ProductFields.Count > 3
select new
{
ProductIDD = p.ProductId,
ProductName = p.ProductName.Contains("hotel"),
NumbeOfProd = p.ProductFields.Count,
totalFields = p.ProductFields.Sum(o => o.FieldId + o.FieldId)
};
Generated follwing sql
SELECT [t0].[ProductId] AS [ProductIDD],
(CASE
WHEN [t0].[ProductName] LIKE '%hotel%' THEN 1
WHEN NOT ([t0].[ProductName] LIKE '%hotel%') THEN 0
ELSE NULL
END) AS [ProductName],
( SELECT COUNT(*) FROM [dbo].[ProductField] AS [t2] WHERE [t2].[ProductId] = [t0].[ProductId] ) AS [NumbeOfProd],
( SELECT SUM([t3].[FieldId] + [t3].[FieldId]) FROM [dbo].[ProductField] AS [t3] WHERE [t3].[ProductId] = [t0].[ProductId]) AS [totalFields]
FROM [dbo].[Product] AS [t0]
WHERE (( SELECT COUNT(*) FROM [dbo].[ProductField] AS [t1] WHERE [t1].[ProductId] = [t0].[ProductId] )) > 3
Why is this CASE statement for ProductName and because of this instead of ProductName i am just getting 0 in my result set. It should generate sql like following, (where ProductName like '%hotel%'
SELECT [t0].[ProductId] AS [ProductIDD],
[ProductName],
( SELECT COUNT(*) FROM [dbo].[ProductField] AS [t2] WHERE [t2].[ProductId] = [t0].[ProductId] ) AS [NumbeOfProd],
( SELECT SUM([t3].[FieldId] + [t3].[FieldId]) FROM [dbo].[ProductField] AS [t3] WHERE [t3].[ProductId] = [t0].[ProductId]) AS [totalFields]
FROM [dbo].[Product] AS [t0]
WHERE (( SELECT COUNT(*) FROM [dbo].[ProductField] AS [t1] WHERE [t1].[ProductId] = [t0].[ProductId] )) > 3
AND t0.ProductName like '%hotel%'
Thanks.
Is it possible to combine these 2 queries or would this make my code too complex?
Also I think there should be a performance gain by combining these queries since I think in the near future my source table could be over 11000 records.
This is what i came up with so far :
Dim lit As LiteralControl
' check characters not in alphabet
Dim r As New Regex("^[^a-zA-Z]+")
Dim query = From o In source.ToTable _
Where r.IsMatch(o.Field(Of String)("nam"))
lit = New LiteralControl(String.Format("letter: {0}, count: {1}<br />", "0-9", query.Count))
plhAlpabetLinks.Controls.Add(lit)
Dim q = From l In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToLower.ToCharArray _
Group Join o In source.ToTable _
On l Equals o.Field(Of String)("nam").ToLowerInvariant(0) Into g = Group _
Select l, g.Count
' iterate the alphabet to generate all the links.
For Each letter In q.AsEnumerable
lit = New LiteralControl(String.Format("letter: {0}, count: {1}<br />", letter.l, letter.Count))
plhAlpabetLinks.Controls.Add(lit)
Next
Kind regards, G.
I am trying to find the list of objects which can be replaced.
Class Letter{
int ID;
string Name;
string AdvCode;
int isDeleted;
}
Class Replacers{
int ID;
string MainAdvCode;
string ReplacesAdvCode;
}
example data:
Replacers
0 455 400
1 955 400
2 955 455
such that if a Letter has and Advcode of 455 and another has a code of 400 the 400 gets marked for deletion. And then if another Letter has a 955 then the 455 gets marked for deletion and the 400 (which is already marked) is marked for deletion.
The problem is with my current code the 400 and 455 is marking itself for deletion?!?!?
Public class Main{
List<Letter> Letters;
List<Replacers> replaces;
//select the ones to replace the replacements aka the little guys
//check if the replacements replacer exists if yes mark deleted
var filterMethodReplacements = new Func<Letter, bool>(IsAdvInReplacements);//Working
var filterMethodReplacers = new Func<Letter, bool>(IsAdvInReplacers);//NOT WORKING????
var resReplacements=letters.Where(filterMethodReplacements);//working
foreach (Letter letter in resReplacements)
{
//select the Replacers aka the ones that contain the little guys
var resReplacers = letters.Where(filterMethodReplacers);
if (resReplacers != null)
letter.isDeleted = 1;
}
}
}
private bool IsAdvInReplacements(Letter letter)
{
return (from a in Replacables where a.ReplaceAdvCode == letter.AdvCode select a).Any();
}
private bool IsAdvInReplacers(Letter letter)
{
//??????????????????????????????
return (from a in Replacables where a.MainAdvCode == letter.AdvCode select a).Any();
}
}